-
-
Save reidsneo/3f9bf435aadd156d907f500c37a13c7d to your computer and use it in GitHub Desktop.
php recursive array search for needle. returns path of keys to value or false
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 | |
// 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