Skip to content

Instantly share code, notes, and snippets.

@itsliamjones
Created May 26, 2016 13:54
Show Gist options
  • Save itsliamjones/53a9b4e85cfc460eb6c22346ceb68f01 to your computer and use it in GitHub Desktop.
Save itsliamjones/53a9b4e85cfc460eb6c22346ceb68f01 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);
}
@devidw
Copy link

devidw commented Feb 9, 2022

Nice one ✨

@Marik-dev
Copy link

Thank you very much.

@medeirosinacio
Copy link

medeirosinacio commented Jan 23, 2023

one refactor

    /**
     * This function extracts all values from a specific key in a multidimensional array, 
     * or all values if key is not provided. It can also remove 
     * duplicates depending on the "uniqueVal" parameter.
     */
    function array_value_recursive(array $arr, ?string $key = null, bool $unique = true): array
    {
        array_walk_recursive($arr, function ($v, $k) use ($key, &$val) {
           if (is_null($key) || ($key && $k == $key)) {
                $val[] = $v;
            }
        });

        return $unique ? array_unique($val ?? []) : $val ?? [];
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment