In this tutorial, you will understand the PHP XOR operator. And going to dive more into some of PHP types through this operator with PHP code examples. Let’s get started with the concept explanation.
The PHP xor operator is one of the PHP logical operators. It is used to merge two boolean results in the condition block to check for. If one part of two both has a true boolean value, so it will return true, otherwise, it will return a false boolean result.
The xor operator can be written as the — “xor” between the two checking parts. It would be like the below code.
<?php
var_dump(
( true ) xor ( false ) // <== Between the two checking parts
); // bool(true)
?>
So the priority of the comparison is for one part of both. If it has a high level than the second part and the other one has a false boolean value. So it will return a true boolean value. If the opposite, it returns a false boolean value. Let’s see that with more examples.
Return a false value if two parts have a false boolean value.
<?php
$x = 5;
$y = 6
$a = 8;
$z = 10;
$part_1 = ( $x > $y ); // => false
$part_2 = ( $z < $a ); // => false
var_dump( $part_1 xor $part_2 ); // the output: bool(false)
?>
Also, it returns a false value if two parts have a true value.
<?php
var_dump(true xor true ); // bool(false)
?>
Also, it can return a true value if one part has a true boolean value.
<?php
var_dump(false xor true ); // bool(true)
?>
One example else with PHP array data type.
<?php
$array_1 = (bool) array( "Ahmed", "Nabeel", "Michael" ); // true
$array_2 = (bool) array(); // false
var_dump( $array_1 xor $array_2 ); // bool(true)
?>
Summary of the PHP XOR Operator
The XOR Operator can be used to check for only one true value in two parts, and that can happen when combining two conditions together.
Let’s summarize that in a few points.
- When the xor operator compares two conditions, it will return a true boolean value if one of the two parts has a true condition —
( ( 10 > 5 ) xor ( 5 > 10 ) )
. - When two parts are returning the true value, so the final result will be a false boolean value —
( ( 5 = 5 ) xor ( 20 > 10 ) )
. - But when the two parts have the same boolean result with a false boolean value, so it would return a false boolean value —
( ( 5 == 10 ) xor ( 6 > 10 ) )
.
That’s all, thank you for reading.