0
0
PhpProgramBeginner · 2 min read

PHP Program to Find Second Largest in Array

You can find the second largest number in an array in PHP by sorting the array with rsort() and then accessing the second element with $array[1].
📋

Examples

Input[3, 5, 1, 4]
Output4
Input[10, 10, 9, 8]
Output9
Input[7]
OutputNo second largest element
🧠

How to Think About It

To find the second largest number, first remove duplicates to avoid counting the same number twice. Then sort the array from largest to smallest. The second element in this sorted list is the second largest number. If the array has less than two unique numbers, there is no second largest.
📐

Algorithm

1
Remove duplicate values from the array.
2
Sort the array in descending order.
3
Check if the array has at least two elements.
4
If yes, return the second element as the second largest.
5
Otherwise, indicate that there is no second largest element.
💻

Code

php
<?php
function findSecondLargest(array $arr) {
    $unique = array_unique($arr);
    rsort($unique);
    if (count($unique) < 2) {
        return "No second largest element";
    }
    return $unique[1];
}

// Example usage
$array = [3, 5, 1, 4];
echo findSecondLargest($array);
Output
4
🔍

Dry Run

Let's trace the array [3, 5, 1, 4] through the code

1

Remove duplicates

Original array: [3, 5, 1, 4], after array_unique: [3, 5, 1, 4]

2

Sort descending

Sorted array: [5, 4, 3, 1]

3

Check length

Array length is 4, which is >= 2

4

Return second largest

Second element is 4

StepArray State
After unique[3, 5, 1, 4]
After sort[5, 4, 3, 1]
💡

Why This Works

Step 1: Remove duplicates

Using array_unique() ensures repeated numbers don't affect finding the second largest.

Step 2: Sort descending

Sorting with rsort() puts the largest numbers first, so the second element is the second largest.

Step 3: Check array length

If there are fewer than two unique numbers, we cannot find a second largest, so we handle that case.

🔄

Alternative Approaches

Single pass scan
php
<?php
function findSecondLargestSinglePass(array $arr) {
    $max = PHP_INT_MIN;
    $secondMax = PHP_INT_MIN;
    foreach ($arr as $num) {
        if ($num > $max) {
            $secondMax = $max;
            $max = $num;
        } elseif ($num > $secondMax && $num < $max) {
            $secondMax = $num;
        }
    }
    if ($secondMax === PHP_INT_MIN) {
        return "No second largest element";
    }
    return $secondMax;
}

// Example usage
$array = [3, 5, 1, 4];
echo findSecondLargestSinglePass($array);
This method finds the second largest in one loop without sorting, which is faster for large arrays but slightly more complex.
Sort ascending and pick second last
php
<?php
function findSecondLargestAsc(array $arr) {
    $unique = array_unique($arr);
    sort($unique);
    if (count($unique) < 2) {
        return "No second largest element";
    }
    return $unique[count($unique) - 2];
}

// Example usage
$array = [3, 5, 1, 4];
echo findSecondLargestAsc($array);
This sorts ascending and picks the second last element. It works but is less intuitive than descending sort.

Complexity: O(n log n) time, O(n) space

Time Complexity

Sorting the array takes O(n log n) time, which dominates the process. Removing duplicates is O(n).

Space Complexity

Creating a unique array uses O(n) extra space. Sorting is done in place or with extra space depending on implementation.

Which Approach is Fastest?

The single pass scan method is O(n) time and O(1) space, making it faster and more memory efficient for large arrays.

ApproachTimeSpaceBest For
Sort descending and pick secondO(n log n)O(n)Simplicity and small arrays
Single pass scanO(n)O(1)Large arrays and performance
Sort ascending and pick second lastO(n log n)O(n)Alternative sorting method
💡
Always remove duplicates before finding the second largest to avoid errors with repeated values.
⚠️
Beginners often forget to remove duplicates, causing the second largest to be the same as the largest if repeated.