The Spaceship operator is one of the many new features introduced in PHP with its 7.0 version. It is a three-way comparison operator.
The conventional comparison operators (<, >, !=, ==, etc.) return true or false (equivalent to 1 or 0). On the other hand, the spaceship operator has three possible return values: -1,0,or 1. This operator can be used with integers, floats, strings, arrays, objects, etc.
Syntax
The symbol used for spaceship operator is “<=>”.
$retval= operand1 <=> operand2
Here, $retval is -1 if operand1 is less than operand2, 0 if both the operands are equal, and 1 if operand1 is greater than operand2.
The spaceship operator is implemented as a combined comparison operator. Conventional comparison operators could be considered mere shorthands for <=> as the following table shows −
Operator
<=> equivalent
$a < $b
($a <=> $b) === -1
$a <= $b
($a <=> $b) === -1 || ($a <=> $b) === 0
$a == $b
($a <=> $b) === 0
$a != $b
($a <=> $b) !== 0
$a >= $b
($a <=> $b) === 1 || ($a <=> $b) === 0
$a > $b
($a <=> $b) === 1
Example 1
The following example shows how you can use the spaceship operator in PHP −
The Null Coalescing operator is one of the many new features introduced in PHP 7. The word “coalescing” means uniting many things into one. This operator is used to replace the ternary operation in conjunction with the isset() function.
Ternary Operator in PHP
PHP has a ternary operator represented by the “?” symbol. The ternary operator compares a Boolean expression and executes the first operand if it is true, otherwise it executes the second operand.
expr ? statement1 : statement2;
Example
Let us use the ternary operator to check if a certain variable is set or not with the help of the isset() function, which returns true if declared and false if not.
Open Compiler
<?php
$x = 1;
$var = isset($x) ? $x : "not set";
echo "The value of x is $var";
?>
It will produce the following output −
The value of x is 1
Now, let’s remove the declaration of “x” and rerun the code −
Open Compiler
<?php
# $x = 1;
$var = isset($x) ? $x : "not set";
echo "The value of x is $var";
?>
The code will now produce the following output −
The value of x is not set
The Null Coalescing Operator
The Null Coalescing Operator is represented by the “??” symbol. It acts as a convenient shortcut to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not null; otherwise it returns its second operand.
$Var=$operand1??$operand2;
The first operand checks whether a certain variable is null or not (or is set or not). If it is not null, the first operand is returned, else the second operand is returned.
Example
Take a look at the following example −
Open Compiler
<?php
# $num = 10;
$val = $num ?? 0;
echo "The number is $val";
?>
It will produce the following output −
The number is 0
Now uncomment the first statement that sets $num to 10 and rerun the code −
Open Compiler
<?php
$num = 10;
$val = $num ?? 0;
echo "The number is $val";
?>
It will now produce the following output −
The number is 10
A useful application of Null Coalescing operator is while checking whether a username has been provided by the client browser.
Example
The following code reads the name variable from the URL. If indeed there is a value for the name parameter in the URL, a Welcome message for him is displayed. However, if not, the user is called Guest.
Assuming that this script “hello.php” is in the htdocs folder of the PHP server, enter http://localhost/hello.php?name=Amar in the URL, the browser will show the following message −
Welcome Amar
If http://localhost/hello.php is the URL, the browser will show the following message −
Welcome Guest
The Null coalescing operator is used as a replacement for the ternary operator’s specific case of checking isset() function. Hence, the following statements give similar results −
PHP recognizes the three dots symbol (…) as the spread operator. The spread operator is also sometimes called the splat operator. This operator was first introduced in PHP version 7.4. It can be effectively used in many cases such as unpacking arrays.
Example 1
In the example below, the elements in $arr1 are inserted in $arr2 after a list of its own elements.
The Spread operator can be used more than once in an expression. For example, in the following code, a third array is created by expanding the elements of two arrays.
However, the use of (…) operator is much more efficient as it avoids the overhead a function call.
Example 4
PHP 8.1.0 also introduced another feature that allows using named arguments after unpacking the arguments. Instead of providing a value to each of the arguments individually, the values from an array will be unpacked into the corresponding arguments, using … (three dots) before the array.
Open Compiler
<?php
function myfunction($x, $y, $z=30) {
echo "x = $x y = $y z = $z";
}
myfunction(...[10, 20], z:30);
?>
It will produce the following output −
x = 10 y = 20 z = 30
Example 5
In the following example, the return value of a function is an array. The array elements are then spread and unpacked.
You would use conditional operators in PHP when there is a need to set a value depending on conditions. It is also known as ternary operator. It first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation.
Ternary operators offer a concise way to write conditional expressions. They consist of three parts: the condition, the value to be returned if the condition evaluates to true, and the value to be returned if the condition evaluates to false.
Operator
Description
Example
? :
Conditional Expression
If Condition is true ? Then value X : Otherwise value Y
Syntax
The syntax is as follows −
condition ? value_if_true : value_if_false
Ternary operators are especially useful for shortening if-else statements into a single line. You can use a ternary operator to assign different values to a variable based on a condition without needing multiple lines of code. It can improve the readability of the code.
However, you should use ternary operators judiciously, else you will end up making the code too complex for others to understand.
Example
Try the following example to understand how the conditional operator works in PHP. Copy and paste the following PHP program in test.php file and keep it in your PHP Server’s document root and browse it using any browser.
Open Compiler
<?php
$a = 10;
$b = 20;
/* If condition is true then assign a to result otheriwse b */
$result = ($a > $b ) ? $a :$b;
echo "TEST1 : Value of result is $result \n";
/* If condition is true then assign a to result otheriwse b */
$result = ($a < $b ) ? $a :$b;
echo "TEST2 : Value of result is $result";
?>
It will produce the following output −
TEST1 : Value of result is 20
TEST2 : Value of result is 10
PHP defines the following set of symbols to be used as operators on array data types −
Symbol
Example
Name
Result
+
$a + $b
Union
Union of $a and $b.
==
$a == $b
Equality
TRUE if $a and $b have the same key/value pairs.
===
$a === $b
Identity
TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
!=
$a != $b
Inequality
TRUE if $a is not equal to $b.
<>
$a <> $b
Inequality
TRUE if $a is not equal to $b.
!==
$a !== $b
Non identity
TRUE if $a is not identical to $b.
The Union operator appends the right-hand array appended to left-hand array. If a key exists in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.
Example: Union Opeator in PHP
The following example shows how you can use the union operator in PHP −
Two arrays are said to be equal if they have the same key-value pairs.
In the following example, we have an indexed array and other associative array with keys corresponding to index of elements in first. Hence, both are equal.
You can use assignment operators in PHP to assign values to variables. Assignment operators are shorthand notations to perform arithmetic or other operations while assigning a value to a variable. For instance, the “=” operator assigns the value on the right-hand side to the variable on the left-hand side.
Additionally, there are compound assignment operators like +=, -= , *=, /=, and %= which combine arithmetic operations with assignment. For example, “$x += 5” is a shorthand for “$x = $x + 5”, incrementing the value of $x by 5. Assignment operators offer a concise way to update variables based on their current values.
The following table highligts the assignment operators that are supported by PHP −
Operator
Description
Example
=
Simple assignment operator. Assigns values from right side operands to left side operand
C = A + B will assign value of A + B into C
+=
Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand
C += A is equivalent to C = C + A
-=
Subtract AND assignment operator. It subtracts right operand from the left operand and assign the result to left operand
C -= A is equivalent to C = C – A
*=
Multiply AND assignment operator. It multiplies right operand with the left operand and assign the result to left operand
C *= A is equivalent to C = C * A
/=
Divide AND assignment operator. It divides left operand with the right operand and assign the result to left operand
C /= A is equivalent to C = C / A
%=
Modulus AND assignment operator. It takes modulus using two operands and assign the result to left operand
C %= A is equivalent to C = C % A
Example
The following example shows how you can use these assignment operators in PHP −
In PHP, logical operators are used to combine conditional statements. These operators allow you to create more complex conditions by combining multiple conditions together.
Logical operators are generally used in conditional statements such as if, while, and for loops to control the flow of program execution based on specific conditions.
The following table highligts the logical operators that are supported by PHP.
Assume variable $a holds 10 and variable $b holds 20, then −
Operator
Description
Example
and
Called Logical AND operator. If both the operands are true then condition becomes true.
(A and B) is true
or
Called Logical OR Operator. If any of the two operands are non zero then condition becomes true.
(A or B) is true
&&
Called Logical AND operator. The AND operator returns true if both the left and right operands are true.
(A && B) is true
||
Called Logical OR Operator. If any of the two operands are non zero then condition becomes true.
(A || B) is true
!
Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.
!(A && B) is false
Example
The following example shows how you can use these logical operators in PHP −
Open Compiler
<?php
$a = 42;
$b = 0;
if ($a && $b) {
echo "TEST1 : Both a and b are true \n";
} else {
echo "TEST1 : Either a or b is false \n";
}
if ($a and $b) {
echo "TEST2 : Both a and b are true \n";
} else {
echo "TEST2 : Either a or b is false \n";
}
if ($a || $b) {
echo "TEST3 : Either a or b is true \n";
} else {
echo "TEST3 : Both a and b are false \n";
}
if ($a or $b) {
echo "TEST4 : Either a or b is true \n";
} else {
echo "TEST4 : Both a and b are false \n";
}
$a = 10;
$b = 20;
if ($a) {
echo "TEST5 : a is true \n";
} else {
echo "TEST5 : a is false \n";
}
if ($b) {
echo "TEST6 : b is true \n";
} else {
echo "TEST6 : b is false \n";
}
if (!$a) {
echo "TEST7 : a is true \n";
} else {
echo "TEST7 : a is false \n";
}
if (!$b) {
echo "TEST8 : b is true \n";
} else {
echo "TEST8 : b is false";
}
?>
It will produce the following output −
TEST1 : Either a or b is false
TEST2 : Either a or b is false
TEST3 : Either a or b is true
TEST4 : Either a or b is true
TEST5 : a is true
TEST6 : b is true
TEST7 : a is false
TEST8 : b is false
In PHP, Comparison operators are used to compare two values and determine their relationship. These operators return a Boolean value, either True or False, based on the result of the comparison.
The following table highligts the comparison operators that are supported by PHP. Assume variable $a holds 10 and variable $b holds 20, then −
Operator
Description
Example
==
Checks if the value of two operands are equal or not, if yes then condition becomes true.
($a == $b) is not true
!=
Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.
($a != $b) is true
>
Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.
($a > $b) is false
<
Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.
($a < $b) is true
>=
Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.
($a >= $b) is false
<=
Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.
($a <= $b) is true
Additionally, these operators can also be combined with logical operators (&&, ||, !) to form complex conditions for decision making in PHP programs.
Example
The following example shows how you can use these comparison operators in PHP −
Open Compiler
<?php
$a = 42;
$b = 20;
if ($a == $b) {
echo "TEST1 : a is equal to b \n";
} else {
echo "TEST1 : a is not equal to b \n";
}
if ($a > $b) {
echo "TEST2 : a is greater than b \n";
} else {
echo "TEST2 : a is not greater than b \n";
}
if ($a < $b) {
echo "TEST3 : a is less than b \n";
} else {
echo "TEST3 : a is not less than b \n";
}
if ($a != $b) {
echo "TEST4 : a is not equal to b \n";
} else {
echo "TEST4 : a is equal to b \n";
}
if ($a >= $b) {
echo "TEST5 : a is either greater than or equal to b \n";
} else {
echo "TEST5 : a is neither greater than nor equal to b \n";
}
if ($a <= $b) {
echo "TEST6 : a is either less than or equal to b \n";
} else {
echo "TEST6 : a is neither less than nor equal to b";
}
?>
It will produce the following output −
TEST1 : a is not equal to b
TEST2 : a is greater than b
TEST3 : a is not less than b
TEST4 : a is not equal to b
TEST5 : a is either greater than or equal to b
TEST6 : a is neither less than nor equal to b
As in any programming language, PHP also has operators which are symbols (sometimes keywords) that are predefined to perform certain commonly required operations on one or more operands.
For example, using the expression “4 + 5” is equal to 9. Here “4” and “5” are called operands and “+” is called an operator.
We have the following types of operators in PHP −
Arithmetic Operators
Comparison Operators
Logical Operators
Assignment Operators
String Operators
Array Operators
Conditional (or Ternary Operators)
This chapter will provide an overview of how you can use these operators in PHP. In the subsequent chapters, we will take a closer look at each of the operators and how they work.
Arithmetic Operators in PHP
We use Arithmetic operators to perform mathematical operations like addition, subtraction, multiplication, division, etc. on the given operands. Arithmetic operators (excluding the increment and decrement operators) always work on two operands, however the type of these operands should be the same.
The following table highligts the arithmetic operators that are supported by PHP. Assume variable “$a” holds 42 and variable “$b” holds 20 −
Operator
Description
Example
+
Adds two operands
$a + $b = 62
–
Subtracts second operand from the first
$a – $b = 22
*
Multiply both operands
$a * $b = 840
/
Divide numerator by de-numerator
$a / $b = 2.1
%
Modulus Operator and remainder of after an integer division
$a % $b = 2
++
Increment operator, increases integer value by one
$a ++ = 43
—
Decrement operator, decreases integer value by one
$a — = 42
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
Comparison Operators in PHP
You would use Comparison operators to compare two operands and find the relationship between them. They return a Boolean value (either true or false) based on the outcome of the comparison.
The following table highligts the comparison operators that are supported by PHP. Assume variable $a holds 10 and variable $b holds 20, then −
Operator
Description
Example
==
Checks if the value of two operands are equal or not, if yes then condition becomes true.
($a == $b) is not true
!=
Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.
($a != $b) is true
>
Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.
($a > $b) is false
<
Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.
($a < $b) is true
>=
Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.
($a >= $b) is false
<=
Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.
($a <= $b) is true
Logical Operators in PHP
You can use Logical operators in PHP to perform logical operations on multiple expressions together. Logical operators always return Boolean values, either true or false.
Logical operators are commonly used with conditional statements and loops to return decisions according to the Boolean conditions. You can also combine them to manipulate Boolean values while dealing with complex expressions.
The following table highligts the logical operators that are supported by PHP.
Assume variable $a holds 10 and variable $b holds 20, then −
Operator
Description
Example
and
Called Logical AND operator. If both the operands are true then condition becomes true.
(A and B) is true
or
Called Logical OR Operator. If any of the two operands are non zero then condition becomes true.
(A or B) is true
&&
Called Logical AND operator. If both the operands are non zero then condition becomes true.
(A && B) is true
||
Called Logical OR Operator. If any of the two operands are non zero then condition becomes true.
(A || B) is true
!
Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.
!(A && B) is false
Assignment Operators in PHP
You can use Assignment operators in PHP to assign or update the values of a given variable with a new value. The right-hand side of the assignment operator holds the value and the left-hand side of the assignment operator is the variable to which the value will be assigned.
The data type of both the sides should be the same, else you will get an error. The associativity of assignment operators is from right to left. PHP supports two types of assignment operators −
Simple Assignment Operator − It is the most commonly used operator. It is used to assign value to a variable or constant.
Compound Assignment Operators − A combination of the assignment operator (=) with other operators like +, *, /, etc.
The following table highligts the assignment operators that are supported by PHP −
Operator
Description
Example
=
Simple assignment operator, Assigns values from right side operands to left side operand
C = A + B will assign value of A + B into C
+=
Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand
C += A is equivalent to C = C + A
-=
Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand
C -= A is equivalent to C = C – A
*=
Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand
C *= A is equivalent to C = C * A
/=
Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand
C /= A is equivalent to C = C / A
%=
Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand
C %= A is equivalent to C = C % A
String Operators in PHP
There are two operators in PHP for working with string data types −
The “.” (dot) operator is PHP’s concatenation operator. It joins two string operands (characters of right hand string appended to left hand string) and returns a new string.
PHP also has the “.=” operator which can be termed as the concatenation assignment operator. It updates the string on its left by appending the characters of right hand operand.
$third=$first.$second;$leftstring.=$rightstring;
Array Operators in PHP
PHP defines the following set of symbols to be used as operators on array data types −
Symbol
Example
Name
Result
+
$a + $b
Union
Union of $a and $b.
==
$a == $b
Equality
TRUE if $a and $b have the same key/value pairs.
===
$a === $b
Identity
TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
!=
$a != $b
Inequality
TRUE if $a is not equal to $b.
<>
$a <> $b
Inequality
TRUE if $a is not equal to $b.
!==
$a !== $b
Non identity
TRUE if $a is not identical to $b.
Conditional Operators in PHP
There is one more operator in PHP which is called conditional operator. It is also known as ternary operator. It first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation.
Operator
Description
Example
? :
Conditional Expression
If Condition is true ? Then value X : Otherwise value Y
Operator Categories in PHP
All the operators we have discussed above can be categorised into following categories −
Unary prefix operators, which precede a single operand.
Binary operators, which take two operands and perform a variety of arithmetic and logical operations.
The conditional operator (a ternary operator), which takes three operands and evaluates either the second or third expression, depending on the evaluation of the first expression.
Assignment operators, which assign a value to a variable.
Operator Precedence in PHP
Precedence of operators decides the order of execution of operators in an expression. For example, in “2+6/3”, division of 6/3 is done first and then the addition of “2+2” takes place because the division operator “/” has higher precedence over the addition operator “+”.
To force a certain operator to be called before other, parentheses should be used. In this example, (2+6)/3 performs addition first, followed by division.
Some operators may have the same level of precedence. In that case, the order of associativity (either left or right) decides the order of operations. Operators of same precedence level but are non-associative cannot be used next to each other.
The following table lists the PHP operators in their decreasing order of precedence −