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
$knownVars = ['apple', 'orange'];
$listToCheck = ['pear', 'banana'];
public function getValidItemsList( $listToCheck )
{
$returnList = [];
foreach($listToCheck as $key => $val)
{
if(in_array($val, $knownVars))
{
array_push($returnList, $val);
}
}
if(empty($returnList))
{
return -1;
}
return $returnList;
}
$validItemsList = getValidItemsList($listToCheck);
if(isset($validItemsList) && $validItemsList != -1 && in_array('apple', $validItemsList))
{
}
if(isset($validItemsList) && $validItemsList != -1 && is_array($validItemsList) && in_array('apple', $validItemsList))
{
}
?>
Hope that can help someone, I know it helped me.