Snippet. PHP. Function is_in_array. The Regular PHP Function in_array "on Steroids"

The regular PHP function in_array is pretty useful, if you want to check whether a value is present in an array. However, if you want to check multiple values you will have to call it multiple times, thus your code becoming hard to read and maintain. The function is_in_array($needle, $haystack) boosts the regular PHP function in_array, with the capability to pass an array of values as needle, and any of the values will be checked in the looked up array (the haystack).

Function is_in_array($needle,$haystack)

//======================== START OF FUNCTION ==========================//
// FUNCTION: is_in_array                                               //
//=====================================================================//
   /**
    * @param mixed $needle
    * @param array $haystack
    * @return boolean
    */
function is_in_array($needle,$haystack){
    if(is_array($needle)==false){
        return in_array($needle, $haystack, true);
    }
    foreach ($needle as $n) {	
        if (in_array($n, $haystack, true) ) {
            return true;
        }
    }
    return false;
}
//=====================================================================//
// FUNCTION: is_in_array                                               //
//========================= END OF FUNCTION ===========================//

Example

The following example shows how to use the function is_in_array:
$fruits_in_store_1 = array('apples','oranges','cherries');
$fruits_in_store_2 = array('apples','oranges','grapes');
$fruits_in_store_3 = array('apples','oranges','tangerines');

$my_diet_list_one_per_day = array('bananas','tangerines');

// Which store to go to?
if(is_in_array($my_diet_list_one_per_day, $fruits_in_store_1)){
    // Go to store 1
} else if(is_in_array($my_diet_list_one_per_day, $fruits_in_store_2)){
    // Go to store 2
} else if(is_in_array($my_diet_list_one_per_day, $fruits_in_store_3)){
    // Go to store 3
}

Updated on: 19 Apr 2024