Skip to content

Instantly share code, notes, and snippets.

@bombsimon
Created September 23, 2019 21:08
Show Gist options
  • Save bombsimon/c2592efb77d169d65cdae6902791a0bb to your computer and use it in GitHub Desktop.
Save bombsimon/c2592efb77d169d65cdae6902791a0bb to your computer and use it in GitHub Desktop.
Find first occurrence of key in PHP array
<?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