PHP Program To Find The Largest Number of Given Values

By Saruque Ahamed Mollick

In this tutorial, you gonna learn how to find out the largest number for some given numerical values.
In PHP, We have a function max() by using this function we can easily get the largest number.

But I will first go for PHP code to find the largest of 3 numbers. By this, we can get the logic first.
Thereafter, We gonna learn the easiest way to find out the largest number among some given numbers. No matter how many numbers are provided to find out the largest numbers among those.

PHP Program to find out the largest of three numbers

<?php
      $num1=20;
      $num2=15;
      $num3=22;
      if($num1>$num2 && $num1>$num3){
      	echo $num1;
      }
      else{
      	if($num2>$num1 && $num2>$num3){
      		echo $num2;
      	}
      	else
      		echo $num3;
      }

?>

This will echo out the largest number of those three numbers.

But now assume that you have more than three numbers or more than that what will you do?

For this, The simple concept is to put all the numbers in an Array and echo out the largest number using the max() function.

let’s see an example

PHP program to echo out the largest number of given numbers

<?php
      $largest=max(15,18,22,56,19,5);
      echo "$largest";

?>

In PHP this function gonna return the maximum value in an Array.

So you may use the below Code too



<?php
      $numbers=array(15,18,22,56,19,5);
      echo max($numbers);

?>

It will also give you the same output.

Also, Read

Check if a string contains a particular word using PHP

How To Generate Random Password In PHP?

 

PHP program to find the largest of three numbers using HTML form as input.

<!DOCTYPE html>
<html>
<head>
  <title>Largest Number</title>
</head>
<body>
<form method="post" action="index.php">
  Enter the first number:<br>
  <input type="text" name="num1"><br>
  Enter the second number:<br>
  <input type="text" name="num2"><br>
  Enter the third number:<br>
  <input type="text" name="num3">
  <br>
  <input type="submit" name="submit">
</form>
</body>
</html>
<?php
if(isset($_POST["submit"])){
      $num1=$_POST["num1"];
      $num2=$_POST["num2"];
      $num3=$_POST["num3"];
      if($num1>$num2 && $num1>$num3){
      	echo $num1;
      }
      else{
      	if($num2>$num1 && $num2>$num3){
      		echo $num2;
      	}
      	else
      		echo $num3;
      }
  }

?>

The above is an example of finding the largest of three numbers where a user can input the numbers via HTML form.

Remove duplicate values from an array in PHP

 

Leave a Reply

Your email address will not be published. Required fields are marked *