Last active
November 20, 2018 13:38
-
-
Save lomholdt/98e42c718c50938c6c0ea85dd6d98e3f to your computer and use it in GitHub Desktop.
A recursive implementation of array_key_exists
This file contains hidden or 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 | |
| function array_key_exists_recursive($key, $arr) | |
| { | |
| if (array_key_exists($key, $arr)) { | |
| return true; | |
| } | |
| foreach ($arr as $currentKey => $value) { | |
| if (is_array($value)) { | |
| return array_key_exists_recursive($key, $value); | |
| } | |
| } | |
| return false; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Your function has a bug.
Inside the foreach, you cannot return unless you're returning true. Otherwise, you will not finish traversing all possible sub-arrays.
Demo:
A similar function is discussed here: https://murviel-info-beziers.com/fonction-recursive-array_key_exists-php/ (in French).