Facebook Page Twitter Page LinkedIn Page
× PHP Examples


A number is said to be positive if it is greater than zero and it is said to be negative if it is less than zero. A number can be checked for zero, positive and negative using if, if-else, nested if-else and short-hand if-else statements.

Method 1: Using If statement

In the below example, if conditional statements are used to check whether a given number is positive or negative.

<?php
function CheckNumber($x) {
  if ($x > 0)
    {$message = "Positive number";}
  if ($x == 0)
    {$message = "Zero";}
  if ($x < 0)
    {$message = "Negative number";}
  echo $message."\n";
}

CheckNumber(5.5);
CheckNumber(-10.8);
?>

The above code will give the following output:

Positive number
Negative number

Method 2: Using If-else statement

It can also be achieved using If-else conditional statements.

<?php
function CheckNumber($x) {
  if ($x > 0)
    {$message = "Positive number";}
  elseif ($x == 0)
    {$message = "Zero";}
  else
    {$message = "Negative number";}
  echo $message."\n";
}

CheckNumber(5.5);
CheckNumber(-10.8);
?>

The above code will give the following output:

Positive number
Negative number

Method 3: Using Nested If-else statement

The above problem can also be solved using nested if-else conditional statements.

<?php
function CheckNumber($x) {
  if ($x >= 0) {
    if ($x > 0)
      $message = "Positive number";
    else
      $message = "Zero";
  }
  else
    $message = "Negative number";
  
  echo $message."\n";
}

CheckNumber(5.5);
CheckNumber(-10.8);
?>

The above code will give the following output:

Positive number
Negative number

Method 4: Using Ternary Operator

Ternary operator can also be used here.

<?php
function CheckNumber($x) {
  $message = ($x > 0)? "Positive number" : 
             (($x == 0)? "Zero" : "Negative number");
             
  echo $message."\n";
}

CheckNumber(5.5);
CheckNumber(-10.8);
?>

The above code will give the following output:

Positive number
Negative number