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

PHP program to find the minimum element in an array



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

Example

 Live Demo

<?php
   function get_min_value($my_array){
      $n = count($my_array);
      $min_val = $my_array[0];
      for ($i = 1; $i < $n; $i++)
         if ($min_val > $my_array[$i])
            $min_val = $my_array[$i];
            return $min_val;
   }
   $my_array = array(56, 78, 91, 44, 0, 11);
   print_r("The lowest value of the array is ");
   echo(get_min_value($my_array));
   echo("
"); ?>

Output

The lowest value of the array is 0

A function named ‘get_min_value()’ 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 lowest value amongst all of them is given as output −

$min_val = $my_array[0];
for ($i = 1; $i < $n; $i++)
   if ($min_val > $my_array[$i])
      $min_val = $my_array[$i];
return $min_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 lowest value of the array is ");
echo(get_min_value($my_array));
Updated on: 2020-08-17T12:04:08+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements