Home > Net >  Highest Array Value in all
Highest Array Value in all

Time:09-27

This works but is there a better way to do this with php, I want to get the highest value in all of the arrays, If someone could explain in easy terms ,-,

<?php
$marks1 = array(360,310,310,330,313,375,456,111,256);
$marks2 = array(350,340,356,330,321);
$marks3 = array(630,340,570,635,434,255,298);
$i=0;



foreach ($marks1 as $value)  
{   
        if($i > $value || $i == 0)
        $i=$value;
        {
          foreach ($marks2 as $value)
            {
                if($i > $value || $i == 0) 
                    $i=$value;
                foreach ($marks3 as $value)
                {
                    if($i < $value || $i == 0)
                        $i=$value; 
                }                                   

            }
        }   
}
echo "$i<br>";

?>

CodePudding user response:

You can merge the arrays together and then use the max function.

$marks1 = array(360,310,310,330,313,375,456,111,256);
$marks2 = array(350,340,356,330,321);
$marks3 = array(630,340,570,635,434,255,298);

$merged = array_merge($marks1, $marks2, $marks3);

$max = max($merged);

CodePudding user response:

If you want to try out with your own max function logic.

You can also try with this way by merging arrays using array_merge function, this will combine all your arrays and will give you the highest value:

<?php
    function get_max_value($my_array){
      $n = count($my_array);
      $max_val = $my_array[0];
      for ($i = 1; $i < $n; $i  )
         if ($max_val < $my_array[$i])
            $max_val = $my_array[$i];
      return $max_val;
    }
   
    $marks1 = array(360,310,310,330,313,375,456,111,256);
    $marks2 = array(350,340,356,330,321);
    $marks3 = array(630,340,570,635,434,255,298);
   
   $my_array = array_merge($marks1, $marks2, $marks3);
   print_r("The highest value of the array is ");
   echo(get_max_value($my_array));
?>

Let me know if it helps.

CodePudding user response:

If your php version more then 7.4 you can use Spread Operator. If not, the best way using array_merge($marks1, $marks2, $marks3)

<?php
$marks1 = array(360,310,310,330,313,375,456,111,256);
$marks2 = array(350,340,356,330,321);
$marks3 = array(630,340,570,635,434,255,298);

$max = max([...$marks1,...$marks2,...$marks3]);

echo $max; // Result: 635

CodePudding user response:

Alternatively, this one can also work for you:

<?php
    
  $marks1 = array(360,310,310,330,313,375,456,111,256);
  $marks2 = array(350,340,356,330,321);
  $marks3 = array(630,340,570,635,434,255,298);
   
  $arr = array_merge($marks1, $marks2, $marks3);
  $b = 0;
  for($i=0;$i<count($arr);$i  )
   {
      if ($arr[$i] > $b)
    {
          $b = $arr[$i];
      }
  }
  echo $b;
?>

// Output:
// 635
  •  Tags:  
  • php
  • Related