-1

I'm pretty new to PHP and i'm stuck in the following scenario. I have an array with some values and I want to get the max value in the array set.

For ex:

$array = array(
     0 => array(
        '1' => '123',
        '2' => '120',
        '3' => '30',
        '4' => '150'
     ),
     1 => array( 
        '1' => '123',
        '2' => '122',
        '3' => '30',
        '4' => '158'
     ),
     2 => array(
        '1' => '123',
        '2' => '129',
        '3' => '300',
        '4' => '150'
     )
);

The value i'm expecting is 300. I have tried the following code and i don't know how to get the maximum value from all the sub arrays.

$max = 0;
foreach( $array as $k => $v ){
  //this is where i need help

 }

Any kind of help would be highly appreciated.

3 Answers3

3

You can flatten your array first using array_merge(...$array), then just use the max() function:

$new_array = array_merge(...$array);
echo max($new_array);

Demo

catcon
  • 1,295
  • 1
  • 9
  • 18
  • Just to clarrify.Why would you use ...$array in array merge –  Aug 21 '20 at 06:36
  • 1
    See [here](https://stackoverflow.com/questions/41124015/meaning-of-three-dot-in-php) – DarkBee Aug 21 '20 at 06:40
  • 2
    `array_merge()` accept a list of arrays as the argument, array_merge(...$array) means `$array` contain the list of array that needed to be merged together. – catcon Aug 21 '20 at 06:41
0

I took @Hirumina's solution and just set $max = $y if $y was > $max

$max = 0;
foreach( $array as $k => $v ) {
    foreach($v as $x => $y) {
        if($y > $max){
            $max = $y;
        }
    }
}
echo $max;
Bijan
  • 7,737
  • 18
  • 89
  • 149
0
$new_array = array_map(function($value){
    return max($value);
}, $array);
echo max($new_array);

Here array_map function will get max value from individual $array and store in $new_array. Then max($new_array) will give you max value.

N.S
  • 139
  • 1
  • 1
  • 13
  • 1
    Code only responses are not recommended on Stack Overflow. Please consider adding comments that explain how this code will help address OP's question. Please read about what to do when someone [answers](https://stackoverflow.com/help/someone-answers) your question. – Joe Ferndz Oct 07 '20 at 03:05
  • Can you please add some comment or explanation how it's. – Srikrushna Oct 07 '20 at 05:24