PHP Program to find the largest element in an array


April 6, 2022, Learn eTutorial
2035

Find the largest element in an array?

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

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

To find the largest 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 lar 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] > lar' if it is true then assign the value of 'a[i]' into the variable lar after the completion of the loop we can print the value of the variable lar as the largest element of the array.

ALGORITHM

Step 1: Initialize an array a[] with values

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

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' and increment the value of variable i in every iteration

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

Step 5: Print the value of the variable lar as the largest element of the array

PHP Source Code

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

                                      

OUTPUT

Largest element in the array is  89