Write a PHP program to check whether a number is positive, negative or zero

Description: Write a PHP program to check whether a number is positive, negative or zero.

Rules and hints:

  • Use if else conditions.
  • Use the correct PHP operators.
  • Also check that the value is a number.
  • Write the logic in a function, so you can test many values.

PHP program to check a positive, negative or zero number

<?php
function checkNumber($number) {
    if (!is_numeric($number)) {
        return "Please enter a number";
    }

    if ($number > 0) {
        return $number . " is a positive number";
    } elseif ($number < 0) {
        return $number . " is a negative number";
    }

    return "The number is zero";
}

echo checkNumber(324) . "<br>";
echo checkNumber(-15) . "<br>";
echo checkNumber(0) . "<br>";
echo checkNumber("abc");
?>

Output:

Tutorials Class - Output Window

324 is a positive number
-15 is a negative number
The number is zero
Please enter a number

How it works

  • is_numeric() checks that the value is a number, so text like “abc” is rejected first.
  • If the number is bigger than 0 it is positive, if it is smaller than 0 it is negative. The only remaining case is zero.
  • Because it is a function, you can call it with different values.

Learn more about the similar topics:
Tutorials
PHP Decision Making
PHP match Expression
Exercises & Assignments
Write a program to check student grade based on marks
Write a program to show day of the week using switch
Write a program to calculate Electricity bill in PHP
Write a simple calculator program in PHP using switch case
Write a PHP program to check if a person is eligible to vote
Write a PHP program to check whether a number is positive, negative or zero
Write a PHP Program to print 5 to 15 using Conditional statements
Interview Questions & Answers
No Content Found.