This sample program is very helpful for the School / College kids who are willing to become a PHP developer.
And in the interviews these kind of questions asked many times. So it is always good to be prepared.
Here is the code:
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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
<html> <head> <title>Find Largest & Smallest numbers in an Array - PHP Programming</title> </head> <body> <h3>PHP Program to find Largest & Smallest numbers in a Array 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); //assign the first value of the above array for the Largest & Smallest variables $largest = $numArray[0]; $smallest = $numArray[0]; //now loop through each numbers and find which is Largest & Smallest numbers in a PHP Array foreach($numArray as $num){ if($num > $largest){ $largest = $num; } else if($num < $smallest){ $smallest = $num; } } //print the output echo "Largest Number is: $largest <br />"; echo "Smallest Number is: $smallest"; } ?> |
Read the comments in the above source code to understand it.
Once you go through the code, you may get the below concepts:
1. How to capture POST value from a HTML form into PHP.
2. How to separate a string with delimiters, (explode() function) and convert into an Array.
3. How to loop through a PHP Array
4. And obviously how to find the Largest / Smallest number from an Array without using any Build-in PHP function.
Demo is here:
Enjoy Programming!
Hi good, job