note 15782 added to function.in-array
| From: | johnplatte-nospam at pobox dot com | Date: | Tue, 02 Oct 2001 23:36:25 +0000 |
| Subject: | note 15782 added to function.in-array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-18487@lists.php.net to get a copy of this message | ||
Starting with ck1@wwwtech.de's nice PHP4 array_in_array(), I found a way to get an
array_in_array() that works with multidimensional arrays using foreach() and recursion. I tested it
*some* -- YMMV, etc.
function array_in_array($needle, $haystack)
{
$return = false;
if (! is_array($haystack)) return false;
if (! is_array($needle)) return in_array($needle, $haystack);
foreach($needle as $needle_element)
{
foreach($haystack as $haystack_element)
{
if (array_in_array($needle_element, $haystack_element))
{
$return = true;
break 2; //both haystack and needle foreaches
}
else
{
if (is_array($haystack_element))
{
foreach($haystack_element as $haystack_another_level)
{
if (array_in_array($needle_element, $haystack_another_level))
{
$return = true;
break 3; //inner haystack, haystack, and needle
}
}
}
}
}
}
return $return;
}
Note that the recursion works because it just gives the results of in_array() if $needle is another
type, so this code won't search multiple dimensions for a non-array. Otherwise, I think it will
work as expected with multiple dimensions.
--
http://www.php.net/manual/en/function.in-array.php
http://master.php.net/manage/user-notes.php?action=edit+15782
http://master.php.net/manage/user-notes.php?action=delete+15782
http://master.php.net/manage/user-notes.php?action=reject+15782