Created
September 23, 2019 21:08
-
-
Save bombsimon/c2592efb77d169d65cdae6902791a0bb to your computer and use it in GitHub Desktop.
Find first occurrence of key in PHP array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$test_arr = array( | |
"a" => array( | |
"aa" => 0, | |
"ab" => 1 | |
), | |
"b" => array( | |
"ba" => array( | |
"baa" => 3, | |
"bab" => 4 | |
) | |
) | |
); | |
$to_find = "bab"; | |
$result = find_key($test_arr, $to_find); | |
var_dump($result); | |
// int(4) | |
function find_key($arr, $key_name) { | |
foreach ($arr as $key => $value) { | |
if ("$key" == $key_name) { | |
return $value; | |
} | |
if (gettype($value) == "array") { | |
$r = find_key($value, $key_name); | |
if ( $r ) | |
return $r; | |
} | |
} | |
return NULL; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment