Tag Archives: in_array

Make your own in_array to go deeper

The function in_array allows you to search a value inside an array, but the problem is that it is not a recursive function, it means that if you have an array into an array, an the value you are looking for is inside it, the function will fail finding it.

Example

//our array in an array with its first value 0
$array = array(array(0));

//searching 0 in the array
if(in_array(0, $array))
echo 'ok';
else
echo 'no';

and of course it fails.

So the best is to make our own in_array function to be sure to match all the time, we do need recursion !

//I have taken the same prototype as the in_array function

function r_in_array($needle, $haystack, $strict = false)
{
static $found = false;

foreach($haystack as $line)
{
if(is_array($line))
r_in_array($needle, $line, $strict);
else if($line == $needle)
{
if($strict)
{
if(gettype($line) === gettype($needle))
$found = true;
}
else
$found = true;
}
}

return $found;
}

This function calls itself to find, if there is, the value ($needle) in the array ($haystack) you give it. I added the $strict which checks if the type is the same when set to true.

Now with examples

//well we want to be sure recursion works :p
$array = array(array(0, 2, array(array(array(array(1, array(4)))))), array(3), 0);

//searching 4 (integer) in $array
if(r_in_array(4, $array))
echo 'found';
else
echo 'not found';

It works !

//searching 4 (string) in $array
if(r_in_array("4", $array))
echo 'found';
else
echo 'not found';

Works too !

//searching 4 (integer) in $array
if(r_in_array("4", $array, true))
echo 'found';
else
echo 'not found';

It doesn’t work because we use the strict mode.

Voilà, you can use this function as you wish, enjoy 🙂