- Instant help with your Php coding problems

PHP in_array function use and examples

In cases when you want to check whether a value exists in an array you can use the in_array  function. This function checks if a value exists in an array. You can use it from PHP version 4. The syntax is the following:

bool in_array ( mixed $what , array $where [, bool $strict = FALSE ] )

By default you simply use only the 2 mandatory parameters ($what and $where) as you can see in the following example:

$myArray = array("Audi","BMW","Lexus","Mercedes");
 
var_dump($myArray);
 
if (in_array("Lexus", $myArray)) {
    echo "Lexus was found in the array<br/>";
}
 
if (in_array("opel", $myArray)) {
    echo "Opel was found in the array<br/>";
}

The strict parameter:

If you want to force the in_array function to check also variable types then, you need to set the optional strict parameter to true as you can see in the next code example:

$myArray = array(10,20,30,40,50);
 
var_dump($myArray);
 
if (in_array("10", $myArray)) {
    echo "A - 10 was found as string in the array without strict<br/>";
}
 
if (in_array("10", $myArray, TRUE)) {
    echo "B - 10 was found as string in the array using strict<br/>";
}

Using in_array to find a key in an associative array

The in_array function only checks the values in the array and so if you want to check the keys in case of an associative array then you need to use the array_key_exists function as demonstrated below:

$myArray = array("Audi"=>"A4","Audi"=>"A6","Lexus"=>"IS","Lexus"=>"LS");
 
var_dump($myArray);
 
if (in_array("Lexus", $myArray)) {
    echo "Lexus was found in the array<br/>"; 
}
 
if (array_key_exists("Lexus", $myArray)) {
    echo "Lexus key was found in the array<br/>";
}

Using in_array to find values in a multidimensional array

The next general question is how to find a value in a multidimensional array. Unfortunately, in_array is not able to handle multi-dimensional arrays so you need to create your own function to solve this problem. However, with a simple recursive function you can do this as you can see in the next example code:

function in_array_multi($needle, $haystack) {
    foreach ($haystack as $item) {
        if ($item === $needle || (is_array($item) & in_array_multi($needle, $item))) {
            return true;
        }
    }
 
    return false;
}
 
$myArray = array(array(10,20),array(11,22),array(111,222));
 
var_dump($myArray);
 
if (in_array(11, $myArray)) {
    echo "11 was found";
}
 
if (in_array_multi(11, $myArray)) {
    echo "11 was found with multi";
}

 

Share "PHP in_array function use and examples" with your friends