Syntax error PHP program to find the maximum element in an array

PHP program to find the maximum element in an array



To find the maximum element in an array, the PHP code is as follows −

Example

 Live Demo

<?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;
   }
   $my_array = array(56, 78, 91, 44, 0, 11);
   print_r("The highest value of the array is ");
   echo(get_max_value($my_array));
   echo("
"); ?>

Output

The highest value of the array is91

A function named ‘get_max_value()’ is defined, that takes an array as parameter. Inside this function, the count function is used to find the number of elements in the array, and it is assigned to a variable −

$n = count($my_array);

The first element in the array is assigned to a variable, and the array is iterated over, and adjacent values in the array are compared, and the highest value amongst all of them is given as output −

$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;

Outside the function, the array is defined, and the function is called by passing this array as a parameter. The output is displayed on the screen −

$my_array = array(56, 78, 91, 44, 0, 11);
print_r("The highest value of the array is");
echo(get_max_value($my_array));
Updated on: 2020-08-17T12:21:27+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements