note 111223 added to function.array-search
| From: | uni_cag at yahoo dot com | Date: | Mon, 28 Jan 2013 13:33:20 +0000 |
| Subject: | note 111223 added to function.array-search | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-193412@lists.php.net to get a copy of this message | ||
A recursive search function that returns all the keys it finds.
<?php
public static function arr_search(array $array, $needle, $break_at_first = false)
{
$ret = array();
foreach ($array as $key => $val)
{
if ( ! is_array($val))
{
if ($needle == $val)
{
$ret[] = $key;
if ($break_at_first)
{
break;
}
}
}
else
{
$sub_ret = arr_search($val, $needle, $break_at_first);
if (count($sub_ret) > 0)
{
$ret[] = $key;
$ret = array_merge($ret, $sub_ret);
if ($break_at_first)
{
break;
}
}
}
}
return $ret;
}
// Example
$arr = array(
'o',
'a' => array(
'b' => 'c',
'd' => 'e',
),
'x' => 'y',
'c',
'k' => array(
'c',
'l' => 'm',
'n' => 'c',
),
'z',
);
arr_search($arr, 'c', false);
/*
Returns:
Array
(
[0] => a
[1] => b
[2] => 1
[3] => k
[4] => 0
[5] => n
)
*/
arr_search($arr, 'c', true);
/*
Returns:
Array
(
[0] => a
[1] => b
)
*/
?>
Some practical usage example:
<?php
$ip_arr = array(
'main' => array(
'head' => '1.2.3.4',
'it' => '1.2.3.5',
'hr' => '1.2.3.6',
'sales' => '1.2.3.7',
),
'other_office' => array(
'sales' => '2.3.4.5',
'marketing' => '2.3.4.6',
)
);
$found = arr_search($ip_arr, $_SERVER['REMOTE_ADDR']);
if (in_array('sales', $found)) // Show sth
if (in_array('it', $found)) // Debug
if (in_array('head', $found)) // Tell the boss everything is just fine!
?>
----
Server IP: 69.147.83.199
Probable Submitter: 78.186.152.111
----
Manual Page -- http://php.net/manual/en/function.array-search.php
Edit -- https://master.php.net/note/edit/111223
Del: integrated -- https://master.php.net/note/delete/111223/integrated
Del: useless -- https://master.php.net/note/delete/111223/useless
Del: bad code -- https://master.php.net/note/delete/111223/bad+code
Del: spam -- https://master.php.net/note/delete/111223/spam
Del: non-english -- https://master.php.net/note/delete/111223/non-english
Del: in docs -- https://master.php.net/note/delete/111223/in+docs
Del: other reasons-- https://master.php.net/note/delete/111223
Reject -- https://master.php.net/note/reject/111223
Search -- https://master.php.net/manage/user-notes.php