PHP Program to check whether the number is positive negative or zero


May 11, 2022, Learn eTutorial
2389

It's a simple basic program with numbers in PHP. We will read a number from the user and check whether it is positive or negative or zero with the use of conditional statements in PHP. For a better understanding of the program, we recommend you go through the following topics in PHP.

How to know a number is positive negative or zero?

In this program, we have to check whether the entered value is positive, negative, or zero. To find that first we read the number and check if the number is greater than zero or less than zero.

  • If the number is greater than 0, then the given number is Positive.
  • If the number is less than 0, the given number is Negative.
  • If the number is equal to 0, the user input is Zero.

How to check whether a number is positive negative or zero using PHP?

In this program, we are accepting the number from the user and assign it to the variable num. Then we check is_numeric(num)is true or false, here we are using the built-in function is_numeric() to check the value of the variable num is a number or not. If it is not a number then print "Enter a valid number" otherwise we have to check the condition num > 0, if true print num is positive or else check the condition num < 0 if true print num is negative otherwise print num is zero.

ALGORITHM

Step 1: Accept the number from the user and assign it to the variable num

Step 2: Then we check the condition '!is_numeric(num)'(in here we are using the built-in function is_numeric() to check the value of the variable is a number or not and inversing it with '!'(not) to check if the entered value is not a number) If it is true the print "Enter a valid number" otherwise go to the next step

Step 3: Check the condition 'num > 0' if true print the value of the variable is positive otherwise go to the next step

Step 4: Check the condition 'num < 0' if true print the value of the variable is negative otherwise print the value of the variable as zero

PHP Source Code

                                          <?php
$num = readline("Enter the number to be checked: \n");
if (!is_numeric($num))
    echo "Enter a valid number";
elseif ($num > 0)
    echo "The entered number $num is positive";
elseif ($num < 0)
    echo "The entered number $num is negative";
else {
    echo "The entered number $num is zero";
}
?
                                      

OUTPUT

Example 1
Enter the number to be checked:  57
The entered number 57 is positive

Example 2
Enter the number to be checked:  -14
The entered number -14 is negative

Example 3
Enter the number to be checked:  0
The entered number 0 is zero

Example 4
Enter the number to be checked:  a
Enter a valid number