Created
October 1, 2018 14:16
-
-
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
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