Last active
May 8, 2018 18:48
-
-
Save kjbrum/b34310d6b08ebeba9b2af155448c0ecb to your computer and use it in GitHub Desktop.
Check if an array key/val(optional) exist in an array and optionally return the values
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 | |
/** | |
* Check if an array key/val(optional) exist in an array and optionally return the values | |
* | |
* @param array $array The array to check for the key/val | |
* @param string $key Key to search for | |
* @param string $value Value to search for | |
* @return bool | |
*/ | |
function r_search_array($array, $key, $value=null, $return=false) { | |
$results = array(); | |
if (is_array($array)) { | |
if (isset($array[$key])) { | |
if ($value) { | |
if ($array[$key] == $value) { | |
return true; | |
} | |
} else { | |
if ($return) { | |
$results[] = $array[$key]; | |
} else { | |
return true; | |
} | |
} | |
} | |
foreach ($array as $subarray) { | |
if ($value) { | |
if (r_search_array($subarray, $key, $value)) { | |
return true; | |
} | |
} else { | |
if ($return) { | |
$results = array_merge($results, r_search_array($subarray, $key, null, true)); | |
} else { | |
if (r_search_array($subarray, $key)) { | |
return true; | |
} | |
} | |
} | |
} | |
} | |
if ($return) { | |
return $results; | |
} else { | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment