Find the maximum value in a PHP array

Below is my array:

Array
(
    [3] => Array
        (
            [2] => 3
            [4] => 1
            [5] => 2
            [6] => 2
        )

    [5] => Array
        (
            [2] => 1
            [3] => 2
            [4] => 3
            [6] => 3
        )

In this array I want to find the maximum number, and if the array contains the same maximum values, we select one maximum value randomly.

Expected result, as shown below:

Array
(
    [3] => Array
        (
            [2] => 3

        )

    [5] => Array
        (

            [4] => 3

        )

    [6] => Array
        (
            [2] => 3

        )

)

Here is what I tried:

$found = Array( [3] => Array ( [2] => 3 [4] => 1 [5] => 2 [6] => 2 ) [5] => Array ( [2] => 1 [3] => 2 [4] => 3 [6] => 3 ) [6] => Array ( [2] => 3 [3] => 2 [4] => 2 [5] => 3 )) 
$fmaxnum = array(); 

foreach($found as $fk => $fv){ 
   $fmaxnum[$fk] = max($fv); 
} 
echo "<pre>";print_r($fmaxnum);echo "</pre>"
+4
source share
3 answers

if you just want to know the highest value, as I understand it

In this array I want to find the maximum number, and if the array contains the same maximum values ​​as one maximum value randomly.

you could just do it

$array = [['3','1','2','2'],['1','2','3','3'],['2','1','1','3']]; 
$result = []; 

foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $value) {
    $result[] = $value;
}

echo max($result);  

this will allow you to select the entire array and click values ​​on $result, then you will have only one array of levels and easily use the functionmax

0

max(), array_keys()

:

$found = Array ( '3' => Array ( '2' => 3 ,'4' => 1, '5' => 2, '6' => 2 ),
                 '5' => Array ( '2' => 1 ,'3' => 2, '4' => 3, '6' => 3 ),
                 '6' => Array ( '2' => 3 ,'3' => 2, '4' => 2, '5' => 3 )
                );
$fmaxnum = array(); 
foreach($found as $fk => $fv){ 
    $max_key = array_keys($fv, max($fv));
    $fmaxnum[$fk] = array(
      ($max_key[0]) => max($fv) /* This will give small index value */  
      /* (count($max_key)-1) => => max($fv) // this will give highest index value */
    );
} 

echo "<pre>";
print_r($fmaxnum);
echo "</pre>";
+3

array_map array_keys:

// supposing $arr is your initial array
$arrMax = array_map(function($v){
    $maximum = max($v);
    return  [array_keys($v, $maximum)[0] => $maximum];
}, $arr);

print_r($arrMax);

:

Array
(
    [3] => Array
        (
            [2] => 3
        )

    [5] => Array
        (
            [4] => 3
        )

    [6] => Array
        (
            [2] => 3
        )
)
+3

All Articles