Skip to content
Advertisement

PHP: Combine array of arrays and get lowest value?

I have an array of arrays that looks like this:

Array
(
    [0] => 26
    [1] => 644
)
Array
(
    [0] => 20
    [1] => 26
    [2] => 644
)
Array
(
    [0] => 26
)
Array
(
    [0] => 47
)
Array
(
    [0] => 47
    [1] => 3
    [2] => 18
)
Array
(
    [0] => 26
    [1] => 18
)
Array
(
    [0] => 26
    [1] => 644
    [2] => 24
    [3] => 181
    [4] => 8
    [5] => 6
    [6] => 41
    [7] => 31
)
Array
(
    [0] => 26
    [1] => 644
    [2] => 24
    [3] => 181
    [4] => 12
    [5] => 25
    [6] => 41
    [7] => 31
)
Array
(
    [0] => 181
)
Array
(
    [0] => 181
)
Array
(
    [0] => 899
)

I need to join all of these arrays into one array, so that I can get the lowest number (in this case it would be 3). I tried to use join($array), however that return only a string with which I cannot determine the lowest number. And min($array) just returns the lowest number of each array. I’m not sure what the right term would be for what I’m looking for so I’m hoping someone can help me.

Advertisement

Answer

Simple one:

$array = [[26, 18], [3], [47, 3], [4, 47, 18], [20, 26, 644]];
echo min(array_merge(...$array));

Splat operator ... makes all your subarrays as arguments to array_merge, which in turn merges all subarrays into one, and standard php function min finds the minimum element in this array.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement