Skip to content

Instantly share code, notes, and snippets.

@ArneGockeln
Created October 1, 2018 14:16
Show Gist options
  • Save ArneGockeln/d2b210456770d306407ff3b6fe9a8cbc to your computer and use it in GitHub Desktop.
Save ArneGockeln/d2b210456770d306407ff3b6fe9a8cbc to your computer and use it in GitHub Desktop.
php recursive array search for needle. returns path of keys to value or false
<?php
// This function searches for needle inside of multidimensional array haystack
// Returns the path to the found element or false
function in_array_multi( $needle, array $haystack ) {
if ( ! is_array( $haystack ) ) return false;
foreach ( $haystack as $key => $value ) {
if ( $value == $needle ) {
return $key;
} else if ( is_array( $value ) ) {
// multi search
$key_result = in_array_multi( $needle, $value );
if ( $key_result !== false ) {
return $key . '_' . $key_result;
}
}
}
return false;
}
// Test
$test = [
'SUBJECT' => [
'STD',
'STK',
'JMK',
3 => [
'TEST'
]
],
'COUNTRY' => [
'USA'
]
];
$key_path = in_array_multi( 'TEST', $test );
if ( $key_path !== false ) {
echo $key_path;
}
// Outputs:
// SUBJECT_3_0
// $test['SUBJECT'][3][0] === 'TEST'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment