Write a program to get second highest number in an array using PHP ?
Last Updated :
23 Jul, 2025
Given an array of integers, the task is to write a program that efficiently finds the second-largest element present in the array.
Example:
Input: arr[] = {13, 14, 15, 16, 17, 18}
Output: The second largest element is 17.
Explanation: The largest element of the array
is 18 and the second largest element is 17
Input: arr[] = {10, 5, 10}
Output: The second largest element is 5.
Explanation: The largest element of the array
is 10 and the second largest element is 5
Input: arr[] = {10, 10, 10}
Output: The second largest does not exist.
Explanation: Largest element of the array
is 10 there is no second largest element
Simple Solution:
Approach: The idea is to sort the array in descending order and then return the second element which is not equal to the largest element from the sorted array.
PHP
<?php
function bubbleSort(&$arr) {
$n = sizeof($arr);
// Traverse through all array elements
for($i = 0; $i < $n; $i++) {
$swapped = False;
// Last i elements are already
// in place
for ($j = 0; $j < $n - $i - 1; $j++) {
// traverse the array from 0 to
// n-i-1. Swap if the element
// found is greater than the
// next element
if ($arr[$j] <$arr[$j+1]) {
$t = $arr[$j];
$arr[$j] = $arr[$j+1];
$arr[$j+1] = $t;
$swapped = True;
}
}
// IF no two elements were swapped
// by inner loop, then break
if ($swapped == False)
break;
}
}
// Driver code to test above
$arr = array(64, 34, 25, 12, 22, 11, 90);
$len = sizeof($arr);
bubbleSort($arr);
if($arr[0] == $arr[1]) {
echo "No element";
}
else {
echo "Second Largest element is ".$arr[1];
}
?>
OutputSecond Largest element is 64
Complexity Analysis:
Worst and Average Case Time Complexity: O(n*n). Worst case occurs when array is reverse sorted.
Best Case Time Complexity: O(n). Best case occurs when array is already sorted.
Auxiliary Space: O(1)
Boundary Cases: Bubble sort takes minimum time (Order of n) when elements are already sorted.
Sorting In Place: Yes
Stable: Yes
Another Approach: Find the second largest element in a single traversal.
Below is the complete algorithm for doing this:
1) Initialize the first as 0 (i.e, index of arr[0] element)
2) Start traversing the array from array[1],
a) If the current element in array say arr[i] is greater
than first. Then update first and second as,
second = first
first = arr[i]
b) If the current element is in between first and second,
then update second to store the value of current variable as
second = arr[i]
3) Return the value stored in second.
PHP
<?php
// PHP program to find second largest
// element in an array
// Function to print the
// second largest elements
function print2largest($arr, $arr_size) {
// There should be atleast
// two elements
if ($arr_size < 2) {
echo(" Invalid Input ");
return;
}
$first = $second = PHP_INT_MIN;
for ($i = 0; $i < $arr_size ; $i++) {
// If current element is
// smaller than first
// then update both
// first and second
if ($arr[$i] > $first) {
$second = $first;
$first = $arr[$i];
}
// If arr[i] is in
// between first and
// second then update
// second
else if ($arr[$i] > $second &&
$arr[$i] != $first)
$second = $arr[$i];
}
if ($second == PHP_INT_MIN)
echo("There is no second largest element\n");
else
echo("The second largest element is "
. $second . "\n");
}
// Driver Code
$arr = array(12, 35, 1, 10, 34, 1);
$n = sizeof($arr);
print2largest($arr, $n);
?>
Output:
The second largest element is 34
Another Approach: Sort the array in descending order using the PHP rsort() method and then return the second element from the sorted array. Here, we have declared a returnSecondHighest() method that accepts an array. By implementing the rsort() method in PHP that will sort the array in descending order. Now, store the second-highest element of the sorted array by using the 1st index of the array in a variable. Here, we declare the user-defined array of numbers & call the returnSecondHighest() method and print the second-highest element of the array.
PHP Code:
PHP
<?php
function returnSecondHighest(array $myarray){
// Sort the array in descending order
rsort($myarray);
// Save the element from the second last position of sorted array
$secondHighest = $myarray[1];
// Return second highest number
return $secondHighest;
}
// Driver code to test above
$arr = array(64, 34, 25, 12, 22, 11, 90);
// Call the function and print output
echo "Second highest number : ".returnSecondHighest($arr);
?>
Output: The time complexity of this program is O(nlogn) as the PHP rsort() method takes O(nlogn) where n is the number of elements in the array parameter.
Second highest number : 64
Using Max Function with Filter
To find the second highest number in an array in PHP using the Max Function with Filter approach, apply max() to an array filtered to exclude the maximum value. Then, retrieve the maximum value from the filtered array, which represents the second highest number.
Example:
PHP
<?php
function returnSecondHighest(array $myarray) {
// Find the maximum value in the array
$max_value = max($myarray);
// Filter out the maximum value to find the new maximum (second highest)
$filtered_array = array_filter($myarray, function($value) use ($max_value) {
return $value < $max_value;
});
// Find the second highest value in the filtered array
$secondHighest = max($filtered_array);
// Return the second highest number
return $secondHighest;
}
// Driver code to test above
$arr = array(64, 34, 25, 12, 22, 11, 90);
// Call the function and print output
echo "Second highest number : " . returnSecondHighest($arr);
?>
Output:
Second highest number : 64
Using Set to Remove Duplicates
This method involves converting the array into a set to remove duplicates, then finding the largest and second-largest values by iterating through the set.
Example: In this example, the findSecondLargest function first removes duplicates from the array using array_unique and array_values. It then checks if there are fewer than two unique elements, in which case it returns a message indicating that the second largest does not exist. Otherwise, it initializes the first and second largest elements to PHP_INT_MIN and traverses the unique array to find the largest and second-largest elements.
PHP
<?php
function findSecondLargest($array) {
// Remove duplicates by converting the array to a set
$uniqueArray = array_values(array_unique($array));
// Check if the array has fewer than 2 unique elements
if (count($uniqueArray) < 2) {
return "The second largest does not exist.";
}
// Initialize first and second largest
$first = $second = PHP_INT_MIN;
// Traverse the array to find the first and second largest elements
foreach ($uniqueArray as $element) {
if ($element > $first) {
$second = $first;
$first = $element;
} elseif ($element > $second) {
$second = $element;
}
}
return $second;
}
// Example usage
$arr1 = [13, 14, 15, 16, 17, 18];
echo "The second largest element is " . findSecondLargest($arr1) . "\n";
// Output: The second largest element is 17
$arr2 = [10, 5, 10];
echo "The second largest element is " . findSecondLargest($arr2) . "\n";
// Output: The second largest element is 5
$arr3 = [10, 10, 10];
echo "The second largest element is " . findSecondLargest($arr3) . "\n";
// Output: The second largest does not exist.
?>
OutputThe second largest element is 17
The second largest element is 5
The second largest element is The second largest does not exist.
Using Two Passe
This method involves making two passes through the array. In the first pass, you find the maximum element. In the second pass, you find the largest element that is not equal to the maximum element. This approach ensures that you efficiently find the second largest element without sorting or using additional data structures.
Example: This approach is simple and efficient, requiring only two passes through the array. It avoids sorting the array or using complex data structures while ensuring the correct result is found.
PHP
<?php
function findSecondLargestTwoPasses($array) {
if (count($array) < 2) {
return "The second largest element does not exist.";
}
// First pass to find the maximum element
$max = max($array);
// Second pass to find the largest element that is not equal to the maximum element
$secondMax = PHP_INT_MIN;
foreach ($array as $value) {
if ($value != $max && $value > $secondMax) {
$secondMax = $value;
}
}
// Check if the second largest element exists
if ($secondMax == PHP_INT_MIN) {
return "The second largest element does not exist.";
}
return $secondMax;
}
// Example usage:
$array = [13, 14, 15, 16, 17, 18];
echo "The second largest element is " . findSecondLargestTwoPasses($array) . "\n";
$array = [10, 5, 10];
echo "The second largest element is " . findSecondLargestTwoPasses($array) . "\n";
$array = [10, 10, 10];
echo findSecondLargestTwoPasses($array) . "\n";
?>
OutputThe second largest element is 17
The second largest element is 5
The second largest element does not exist.
Using a Heap Data Structure
To find the second largest element efficiently, you can use a max-heap data structure. This approach is particularly useful when dealing with large datasets.
Example: In this example we use a max heap to find the second largest element in an array. It inserts array elements into the heap, extracts the largest, then finds and returns the second largest.
PHP
<?php
function findSecondLargestWithHeap($arr) {
if (count($arr) < 2) {
return "The second largest element does not exist.";
}
// Create a max heap from the array
$maxHeap = new SplMaxHeap();
foreach ($arr as $value) {
$maxHeap->insert($value);
}
// Extract the largest element
$first = $maxHeap->extract();
// Extract the second largest element
while (!$maxHeap->isEmpty()) {
$second = $maxHeap->extract();
if ($second < $first) {
return "The second largest element is $second";
}
}
return "The second largest element does not exist.";
}
$arr = [13, 14, 15, 16, 17, 18];
echo findSecondLargestWithHeap($arr);
?>
OutputThe second largest element is 17
Similar Reads
PHP Tutorial PHP is a popular, open-source scripting language mainly used in web development. It runs on the server side and generates dynamic content that is displayed on a web application. PHP is easy to embed in HTML, and it allows developers to create interactive web pages and handle tasks like database mana
8 min read
Basics
PHP SyntaxPHP, a powerful server-side scripting language used in web development. Itâs simplicity and ease of use makes it an ideal choice for beginners and experienced developers. This article provides an overview of PHP syntax. PHP scripts can be written anywhere in the document within PHP tags along with n
4 min read
PHP VariablesA variable in PHP is a container used to store data such as numbers, strings, arrays, or objects. The value stored in a variable can be changed or updated during the execution of the script.All variable names start with a dollar sign ($).Variables can store different data types, like integers, strin
5 min read
PHP | FunctionsA function in PHP is a self-contained block of code that performs a specific task. It can accept inputs (parameters), execute a set of statements, and optionally return a value. PHP functions allow code reusability by encapsulating a block of code to perform specific tasks.Functions can accept param
8 min read
PHP LoopsIn PHP, Loops are used to repeat a block of code multiple times based on a given condition. PHP provides several types of loops to handle different scenarios, including while loops, for loops, do...while loops, and foreach loops. In this article, we will discuss the different types of loops in PHP,
4 min read
Array
PHP ArraysArrays are one of the most important data structures in PHP. They allow you to store multiple values in a single variable. PHP arrays can hold values of different types, such as strings, numbers, or even other arrays. Understanding how to use arrays in PHP is important for working with data efficien
5 min read
PHP Associative ArraysAn associative array in PHP is a special array where each item has a name or label instead of just a number. Usually, arrays use numbers to find things. For example, the first item is at position 0, the second is 1, and so on. But in an associative array, we use words or names to find things. These
4 min read
Multidimensional arrays in PHPMulti-dimensional arrays in PHP are arrays that store other arrays as their elements. Each dimension adds complexity, requiring multiple indices to access elements. Common forms include two-dimensional arrays (like tables) and three-dimensional arrays, useful for organizing complex, structured data.
5 min read
Sorting Arrays in PHPSorting arrays is one of the most common operation in programming, and PHP provides a several functions to handle array sorting. Sorting arrays in PHP can be done by values or keys, in ascending or descending order. PHP also allows you to create custom sorting functions.Table of ContentSort Array in
4 min read
OOPs & Interfaces
MySQL Database
PHP | MySQL Database IntroductionWhat is MySQL? MySQL is an open-source relational database management system (RDBMS). It is the most popular database system used with PHP. MySQL is developed, distributed, and supported by Oracle Corporation. The data in a MySQL database are stored in tables which consists of columns and rows.MySQL
4 min read
PHP Database connectionThe collection of related data is called a database. XAMPP stands for cross-platform, Apache, MySQL, PHP, and Perl. It is among the simple light-weight local servers for website development. Requirements: XAMPP web server procedure: Start XAMPP server by starting Apache and MySQL. Write PHP script f
2 min read
PHP | MySQL ( Creating Database )What is a database? Database is a collection of inter-related data which helps in efficient retrieval, insertion and deletion of data from database and organizes the data in the form of tables, views, schemas, reports etc. For Example, university database organizes the data about students, faculty,
3 min read
PHP | MySQL ( Creating Table )What is a table? In relational databases, and flat file databases, a table is a set of data elements using a model of vertical columns and horizontal rows, the cell being the unit where a row and column intersect. A table has a specified number of columns, but can have any number of rows. Creating a
3 min read
PHP Advance
PHP SuperglobalsPHP superglobals are predefined variables that are globally available in all scopes. They are used to handle different types of data, such as input data, server data, session data, and more. These superglobal arrays allow developers to easily work with these global data structures without the need t
6 min read
PHP | Regular ExpressionsRegular expressions commonly known as a regex (regexes) are a sequence of characters describing a special search pattern in the form of text string. They are basically used in programming world algorithms for matching some loosely defined patterns to achieve some relevant tasks. Some times regexes a
12 min read
PHP Form HandlingForm handling is the process of collecting and processing information that users submit through HTML forms. In PHP, we use special tools called $_POST and $_GET to gather the data from the form. Which tool to use depends on how the form sends the dataâeither through the POST method (more secure, hid
4 min read
PHP File HandlingIn PHP, File handling is the process of interacting with files on the server, such as reading files, writing to a file, creating new files, or deleting existing ones. File handling is essential for applications that require the storage and retrieval of data, such as logging systems, user-generated c
4 min read
PHP | Uploading FileHave you ever wondered how websites build their system of file uploading in PHP? Here we will come to know about the file uploading process. A question which you can come up with - 'Are we able to upload any kind of file with this system?'. The answer is yes, we can upload files with different types
3 min read
PHP CookiesA cookie is a small text file that is stored in the user's browser. Cookies are used to store information that can be retrieved later, making them ideal for scenarios where you need to remember user preferences, such as:User login status (keeping users logged in between sessions)Language preferences
9 min read
PHP | SessionsA session in PHP is a mechanism that allows data to be stored and accessed across multiple pages on a website. When a user visits a website, PHP creates a unique session ID for that user. This session ID is then stored as a cookie in the user's browser (by default) or passed via the URL. The session
7 min read