• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
webarchers

webarchers

A perfect Blog Junction

  • About Us
  • Hire A Developer
  • Contact
Web Development > PHP > How to find the second highest number from an array in PHP

How to find the second highest number from an array in PHP

July 18, 2022 by Nitin Sharma Leave a Comment

How-to-get-second-largest-number-from-array

Today we are going to learn how to find the second largest number from an array using php. This question is often asked by interviewers.  So, let’s write php code to get second largest number from given array.

For example:

Given $array=array(2,4,3,11,2,86,34,1);

PHP Code to get the second largest number from given array

<?php 
function findSecondMax(array $arr) {
    $max = PHP_INT_MIN;
    $secondMax = PHP_INT_MIN;
    foreach($arr as $number) {
        if($number > $max) {
            $secondMax = $max;
            $max = $number;
        }
        if($number > $secondMax && $number < $max) {
            $secondMax = $number;
        }
    }
    return $secondMax;
}
$array=array(2,4,3,11,2,86,34,1);
echo findSecondMax($array); //output will be 34
?>

What we did here?

We used PHP_INT_MIN which returns the smallest possible number. We took two variables $max and $secondMax and in the loop we checked if compare each $numbers with $max. If the $number is grater than $max then the biggest digit would be the $number and the $max would be the $secondMax. This is the way you write PHP code to get the second largest number from an array.

That’s it.

Filed Under: Latest, PHP, Web Development

Primary Sidebar

Search Here

Featured Posts

How to find the second highest number from an array in PHP

More from this category

  • Top 10 Popular Magento 2 Interview Questions in 2021
  • Magento 2: Get All Product and Stock details using Rest APIs

Latest Posts

  • How to find the second highest number from an array in PHP
  • Top 10 Popular Magento 2 Interview Questions in 2021
  • Magento 2: Get All Product and Stock details using Rest APIs
  • How to create Magento 2 REST API | Magento 2 REST API example
  • [Solution] Popup Minicart when product add to the cart Magento 2

Categories

  • Blog Marketing (2)
  • Content Creation (3)
  • Content Marketing (4)
  • Email Marketing (1)
  • Facebook Marketing (1)
  • How To (2)
  • Infographics (1)
  • JavaScript (1)
  • Latest (1)
  • Local SEO (1)
  • Magento 2 (8)
  • PHP (3)
  • SEO (6)
  • SEO Updates (4)
  • SMO (2)
  • Top 10 (8)
  • Video Marketing (2)
  • Web Development (16)
  • What's Hot (4)
  • WordPress (4)
  • YouTube Channel (2)

Meet Author

I’m a web developer and a blogger as well. I love to create websites and develop what I imagine. Writing is my hobby and I do it well.

Copyright © 2022 WebArchers built with ❤ and Genesis

  • About
  • Contact