# searching recursively a value in an array

#### Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on
Hi everyone,

I just wanted to propose this piece of code which is searching
recursively a value in an array... and let you indicate me if there is
an error...

function in_array_recursive(\$array, \$val)
{
\$r = false;
if(is_array(\$array))
foreach(\$array as \$a => \$b)
if(\$a == \$val )
\$r = true;
elseif( in_array_recursive(\$b, \$val))
\$r = true;
else
if(\$array == \$val)
\$r = true;
return \$r;
}

I guess we could optimise it making a return each time I make a "\$r ="
:

function in_array_recursive(\$array, \$val)
{
if(is_array(\$array))
foreach(\$array as \$a => \$b)
if(\$a == \$val )
return true;
elseif( in_array_recursive(\$b, \$val))
return true;
else
if(\$array == \$val)
return true;
return false;
}

Thanks,
JR.

## Re: searching recursively a value in an array

Ok, it seems There is a mistake here, we need not to use the "else"
word :

function in_array_recursive(\$array, \$val)
{//search recursevly a value on an array
//this value can be key or value of the arrays

if(is_array(\$array))
foreach(\$array as \$a => \$b)
if(\$a == \$val )
return true;
elseif( in_array_recursive(\$b, \$val))
return true;

if(\$array == \$val)
return true;

return false;
}