Sunday, April 23, 2017

PHP Program to find Largest & Smallest numbers in an Array

<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</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";

    }    

?>

No comments:

Post a Comment