note 126259 added to function.array-search
| From: | moe at moose dot at | Date: | Wed, 21 Jul 2021 10:39:54 +0000 |
| Subject: | note 126259 added to function.array-search | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-216629@lists.php.net to get a copy of this message | ||
I needed a function, that returns a value by specifying a keymap to the searched value in a
multidimensional array and came up with this.
$s is the keymap to the needle and $a the haystack array.
<?PHP
// search keymap $s in array $a
function get_key_in_array($s, $a)
{
if(is_array($s) && is_array($a[key($s)])) {
return get_key_in_array(reset($s), $a[key($s)]);
} else {
if(is_array($s)) $s = reset($s);
return isset($a[$s])?$a[$s]:false;
}
}
// usage examples
// ------------------------------
$arr = ['foo'=>['bar'=>['baz'=>77]]];
$s = ['foo'=>['bar'=>'baz']];
var_dump(get_key_in_array($s,$arr));
$s = ['foo'=>['bar'=>['baz']]];
var_dump(get_key_in_array($s,$arr));
$s = ['foo'=>['bar'=>['nix']]];
var_dump(get_key_in_array($s,$arr));
$s = ['foo'=>'bar'];
var_dump(get_key_in_array($s,$arr));
$s = ['foo'];
var_dump(get_key_in_array($s,$arr));
$s = 'foo';
var_dump(get_key_in_array($s,$arr));
?>
----
Server IP: 45.112.84.4
Probable Submitter: 45.112.85.242 (proxied: 178.114.170.85)
----
Manual Page -- https://php.net/manual/en/function.array-search.php
Edit -- https://main.php.net/note/edit/126259
Del: integrated -- https://main.php.net/note/delete/126259/integrated
Del: useless -- https://main.php.net/note/delete/126259/useless
Del: bad code -- https://main.php.net/note/delete/126259/bad+code
Del: spam -- https://main.php.net/note/delete/126259/spam
Del: non-english -- https://main.php.net/note/delete/126259/non-english
Del: in docs -- https://main.php.net/note/delete/126259/in+docs
Del: other reasons-- https://main.php.net/note/delete/126259
Reject -- https://main.php.net/note/reject/126259
Search -- https://main.php.net/manage/user-notes.php