Write a PHP code to find second largest number in array. Given an unsorted array, we have to write a PHP program to find the second largest number in an array.

Apart from solving this problem. We have to focus on time complexity. As the time complexity of an algorithm is very important in terms of an interview.

For example – Let’s take an array.

Input – arr[] = { 4, 9, 5, 2, 8, 0, 3, 22}

Output – 9

The second largest element in this array is 9. Think for a moment, how do you write a PHP script to find the second largest number in an array? There are multiple ways to solve this problem. Which approach you prefer and why?

## How to Second Largest Number in Array – PHP

**Approach 1:**

One approach is to sort the array. After sorting, pick the element at n-2 position where n is the size of an array. But the time complexity of this approach is O(nlogn).

1 2 3 4 5 6 7 8 9 | function secondHighest(array $arr) { sort($arr); echo $arr[sizeof($arr)-2]; } secondHighest(array( 4, 9, 5, 2, 8, 0, 3, 22)); |

**Approach 2:**

Traverse an array and maintain two indexes max and second max. The code for this approach is written below.

## PHP Code to Find Second Largest Number in an Array

PHP provides several functions for sorting an array. After sorting an array, we can easily print the second largest element. But let’s do without using any inbuilt functions.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | /** * * @param array $arr * @return second highest number of an array */ function findSecondMax(array $arr) { //If array is empty then return if(empty($arr)) { return; } /* * Initialize max and second max with negative value */ $max = -1; $secondMax = -1; //Traverse an array foreach($arr as $number) { //If it's greater than the value of max if($number > $max) { $secondMax = $max; $max = $number; } //If array number is greater than secondMax and less than max if($number > $secondMax && $number < $max) { $secondMax = $number; } } return $secondMax; } $arr = array(70, 4, 8, 10, 14, 9, 7, 6, 5, 3, 2); $second_maximum = findSecondMax($arr); echo "Second Highest Element is ".$second_maximum; |