Skip to content

Instantly share code, notes, and snippets.

@synsa
Forked from itsliamjones/array-value-recursive.php
Created September 16, 2022 07:39
Show Gist options
  • Save synsa/86221d6c956db1caaf52627db0288a7e to your computer and use it in GitHub Desktop.
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
<?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