How to use sort() Function In PHP

The sort() function sorts the array in ascending order. After sorting, the largest element will be the last element in the array.

Example: This example shows the use of the above-mentioned approach.

PHP
<?php

// Declare an array
$arr = [10, 20, 30, 40, 50];

// Sort the array
sort($arr);

// The largest element is the 
// last element after sorting
$largest = $arr[count($arr) - 1];

echo "The Largest Element is: " . $largest;

?>

Output
The Largest Element is: 50

Explanation:

  • $arr is the array containing the elements.
  • sort($arr) sorts the array in ascending order.
  • The largest element is the last element of the sorted array, accessed by count($arr) – 1.

How to Find the Largest Element in an Array in PHP?

Given an array containing some elements, the task is to find the largest element from an array in PHP. PHP provides several ways to achieve this, each with its own advantages and use cases.

Below are the approaches to find the largest element in an array in PHP:

Table of Content

  • Using max() Function
  • Using a Loop
  • Using sort() Function
  • Using reduce() with Anonymous Function

Similar Reads

Using max() Function

The max() function is a built-in PHP function that returns the largest value from an array or a set of values....

Using a Loop

You can use a loop to iterate through the array and find the largest element manually. This approach is more flexible and can be used when additional logic is required....

Using sort() Function

The sort() function sorts the array in ascending order. After sorting, the largest element will be the last element in the array....

Using reduce() with Anonymous Function

The array_reduce() function iteratively reduces the array to a single value using a callback function....