update page now

Voting

: six minus two?
(Example: nine)

The Note You're Voting On

rik at mmod dot co
7 years ago
Using is_array prior to an in_array within an if clause will safely escape a check against a variable that could potentially be a non-array when using in_array.  For instance:

NOTE: A real use case might be that we have a list of possible flags which  in a database we have stored whether each of the flags are 0 or 1.  We want a list of the flags which have the value of 1 to be returned. 

Our example here will not use so many technical artifacts, but will be based on similar logic just to get the point across.

<?php

// We have a list of known values
$knownVars = ['apple', 'orange'];

// A list of values to check
$listToCheck = ['pear', 'banana'];

// And a method that takes a list of values to check and returns a new list
// of the items from said list that are found to be valid...
public function getValidItemsList( $listToCheck /*['pear', 'banana']*/)
{
    $returnList = [];
    foreach($listToCheck as $key => $val)
    {
        if(in_array($val, $knownVars))
        {
            array_push($returnList, $val);
        }
    }

    if(empty($returnList))
    {
        // We have a special case if there were no valid items found, which is the case we are going over
        return  -1;
    }

    // Otherwise, normally returns a list of the items that were found to be valid
    return $returnList;
}

// Call the method and check for any valid items that can be used for some purpose
$validItemsList =  getValidItemsList($listToCheck);

// In this usage we could potentially get an exception because
// in_array() expects an array for argument #2, checking that the value != -1 does not escape the if statement:
if(isset($validItemsList) && $validItemsList != -1 && in_array('apple', $validItemsList))
{
    //...
}

// In this usage, we break free from the if statement safely:
if(isset($validItemsList) && $validItemsList != -1 && is_array($validItemsList) && in_array('apple', $validItemsList))
{
    //...
}

?>

Hope that can help someone, I know it helped me.

<< Back to user notes page

To Top