Write a program to get second highest number in an array using PHP ?
Last Updated :
10 Jul, 2024
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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read