How to Use Not Equal Operator in PHP with Examples

Comparison operators are key features in PHP for evaluating expressions and making decisions based on their results. One such operator is the not equal operator, which is used to compare two values and return a Boolean result indicating whether they are not equal. PHP developers can use this operator to write efficient and effective code that can handle a wide range of scenarios.

This article will go through the not equal operator in PHP, its syntax, and how to use it with examples.

How to Use Not Equal Operator in PHP with Examples

The not equal operator is a comparison operator that returns a Boolean value of true if the two values being compared are not equal and false otherwise.

The table below presents the usage of not-equal operators in PHP with corresponding symbols, an example, and the resulting output.

Operator Symbol

Example

Result

!= $x != $y Returns true if x is not equal to y
<>  $x <> $y Returns true if x is not equal to y

The not-equal operator returns the value true if the left-hand operand is not equal to the right-hand operand otherwise the output is false.

Note: The != and <> operators can be used interchangeably in PHP.

Example 1

In the example below, a comparison has been made between two variables, a and b using the not-equal operator.

<?php
$a = 10;
$b = 10;
var_dump($a != $b);
?>

 
Or:

<?php
$a = 10;
$b = 10;
var_dump($a <> $b);
?>

 
Since they are equal, the output will be a boolean value of “false”.

Output

 

Example 2

In the below-given code, the not equal operator is used to check the value of the variable a is equal to 10 or not, if the value is not equal to 10 and the condition is true the code inside the block will be executed otherwise the first statement outside the block will be the output:

<?php
$a = 5;
if ($a != 10) {
    echo "a is not equal to 10";
}
?>

 
Since the value of a is not equal to 10, the output “a is not equal to 10” will be displayed in the console.

Output

 

Example 3

The not equal operator in PHP can also be used in combination with the while loop, as demonstrated in the following example.

<?php
$i = 1;
while($i != 5) {
  echo "The value of i is: " . $i . "\n";
  $i++;
}
?>

 
The above code prints the value of a variable i from 1 to 4. The while loop terminates when the value of i is not equal to 5, which is checked using the not equal operator in the condition.

Output

 

Conclusion

The not equal operator is an important PHP feature that allows developers to compare two values and return a Boolean result indicating their inequality. This article illustrates its implementation and usage, highlighting its syntax along with examples to help programmers understand and apply it in their programs.



from https://ift.tt/r7UcBET

Post a Comment

0 Comments