These kind of question are asked many time in Interviews to confuse the candidates. It’s actually much easier than using loops.
So how to find the largest and smallest value in an array without using loop?
It’s very simple, we have min() and max() functions already available in PHP itself, min() returns smallest value and max() returns largest value. Using these function I have written an example script below just go through it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<html> <head> <title>Find Largest & Smallest numbers in an Array without using Loop - PHP Programming</title> </head> <body> <h3>PHP Program to find Largest & Smallest numbers in a Array without using loop by <a href="tutorialsmade.com">Tutorialsmade.com</a></h3> Enter the Numbers separated by Commas <br /> (eg: 12,23,56) <br /><br /> <form method="post"> <input type="text" name="numbers"/> <button type="submit">Check</button> </form> </body> </html> <?php if($_POST) { //get the post value from form $numbers = $_POST['numbers']; //separate the numbers and make into array $numArray = explode(',', $numbers); //use max() and min() functions to print the largest and smallest number print "Largest Number is: ".max($numArray)."<br />"; print "Smallest Number is: ".min($numArray); } ?> |
Enjoy the day.