note 126259 deleted from function.array-search by crell

From: Date: Thu, 31 Mar 2022 20:49:12 +0000
Subject: note 126259 deleted from function.array-search by crell
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-217968@lists.php.net to get a copy of this message
Note Submitter: moe at moose dot at ---- 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)); ?>

« previous php.notes (#217968) next »