Search code examples
phparrays

Get all values from multidimensional array


Let's say, I have an array like this:

$array = [
    'car' => [
        'BMW' => 'blue',
        'toyota' => 'gray'
        ],
    'animal' => [
        'cat' => 'orange',
        'horse' => 'white'
        ]
    ];

Then, I want to get all the values (the colour, 'blue', 'gray', 'orange', 'white') and join them into a single array. How do I do that without using foreach twice?

Thanks in advance.


Solution

  • Try this:

    function get_values($array){
        foreach($array as $key => $value){
            if(is_array($array[$key])){
                print_r (array_values($array[$key]));
            }
        }
    }
    
    get_values($array);