find the largest element in an array in php

To find the largest element in an array in PHP, you can make use of the max() function provided by the language.

main.php
$array = array(5, 9, 3, 2, 7, 8);
$largest = max($array);
echo "The largest element in the array is: $largest";
112 chars
4 lines

This will output:

main.php
The largest element in the array is: 9
39 chars
2 lines

Here, we first initialize an array of integers with some random values. Then we use the max() function to find the largest element in the array. The result is stored in the $largest variable, which we then display using the echo statement.

You can also use the ... (spread) operator to pass an array to the max() function:

main.php
$array = array(5, 9, 3, 2, 7, 8);
$largest = max(...$array);
echo "The largest element in the array is: $largest";
115 chars
4 lines

This will output the same result as above.

gistlibby LogSnag