Forked from itsliamjones/array-value-recursive.php
Created
September 16, 2022 07:39
-
-
Save synsa/86221d6c956db1caaf52627db0288a7e to your computer and use it in GitHub Desktop.
Get all values from specific key in a multidimensional array, similar to array_columns
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 | |
/** | |
* Get all values from specific key in a multidimensional array | |
* | |
* @param string $key key(s) of value you wish to extract | |
* @param array $arr where you want | |
* | |
* @return null|string|array | |
*/ | |
function array_value_recursive($key, array $arr) | |
{ | |
$val = array(); | |
array_walk_recursive($arr, function ($v, $k) use ($key, &$val) { | |
if ($k == $key) array_push($val, $v); | |
}); | |
return count($val) > 1 ? $val : array_pop($val); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment