How to find largest number in array using PHP?

Member

by viviane , in category: PHP , 2 years ago

How to find largest number in array using PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@viviane You can use max() function to find largest number in array using PHP, here is code as example:


1
2
3
4
5
6
<?php

$arr = [1, 2, 15, 3, 4, 5];

// Output: 15
echo max($arr); 

Member

by freddy , a year ago

@viviane 

You can use the max() function in PHP to find the largest number in an array. Here's an example:

1
2
3
$numbers = array(1, 2, 3, 4, 5);
$largest = max($numbers);
echo $largest; // Output: 5


Alternatively, you can also use a foreach loop to iterate through the array and compare each element to a variable storing the current largest number, like this:

1
2
3
4
5
6
7
8
$numbers = array(1, 2, 3, 4, 5);
$largest = 0;
foreach ($numbers as $number) {
    if ($number > $largest) {
        $largest = $number;
    }
}
echo $largest; // Output: 5


You can also use the php function array_reduce() to achieve this

1
2
3
4
5
$numbers = array(1, 2, 3, 4, 5);
$largest = array_reduce($numbers, function ($a, $b) {
    return max($a, $b);
});
echo $largest; // Output: 5