PHP Program to find the smallest element in an array


March 3, 2022, Learn eTutorial
1310

Find the smallest element in an array?

In this program, we are going to find the smallest element in the array. To find the smallest element we have to compare every element with each other and print the smallest among them. For example, the array is 45,20,69,52,31  then the output will be 20.

How to find the smallest element in an array using PHP?

To find the smallest among the element we are taking the static values which are assigned to the array a[]. Then we have to assign the first element of the array to the variable sma and also assign the size of the array into the variable s using the built-in function count() and after that, we have to assign the value 0 into the variable i and perform the loop until the condition 'i < s' and also increment the value of the variable i in every iteration and in the loop block we have to check the condition 'a[i] < sma' if it is true then assign the value of 'a[i]' into the variable sma after the completion of the loop we can print the value of the variable sma as the smallest element of the array.

ALGORITHM

Step 1: Initialize an array a[] with values

Step 2: Assign the value of a[0] to the variable sma

Step 3: Assing the size of an array into the variable s using the built-in function count()

Step 4: Assign the value 0 into the variable i and perform the sub-step until the condition 'i < s' becomes false and increment the value of variable i in every iteration

        (i) Check the condition 'a[i] > sma' then assign the value of a[i] into the variable sma

Step 5: Print the value of the variable sma as the smallest element of the array

PHP Source Code

                                          <?php
$a = array(10, 30, 89, 64, 23);
$sma = $a[0];
$s = count($a);
for ($i = 0; $i < $s; $i++) {
    if ($a[$i] < $sma)
        $sma = $a[$i];
}
echo "Smallest element in the array is  $sma";
?>
                                      

OUTPUT

Smallest element in the array is  10