PHP Code to Find Second Largest Number in Array

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:

Subscribe Our Tutorials

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).

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.