Operators perform operations on the values stored in the variables. Operators are symbols that tell the PHP compiler to perform specific actions. This module will dive deep into how to perform the operations on the variables using operators in PHP.
Read Also: PHP Constants
Index
Operators in PHP
Operators are constructs that behave like functions and tell the processor to perform some actions. For example, the operator (+) tells PHP to add two variables. PHP operators perform operations on variables or values. An operator takes values known as operands and performs operations on them, and gives a result. PHP borrows most of its operators from Perl and C. Just like various other programming languages, PHP also supports multiple operators.
The following are the most common operators used in PHP.
- Arithmetic Operators
- Logical or relational operators
- Comparison Operators
- Conditional or ternary Operators
- Assignment Operators
- Spaceship Operators
- Array Operators
- Increment/Decrement Operators
- String Operators
We can also categorize the operators on behalf of operands. They categorize in 3 forms.
- Unary Operators: Works on single operand such as ++, — etc.
- Binary Operators: Works on two operands such as +,-,*, etc.
- Ternary operators: Works on three operands such as “?:”.
A detailed description of each of these Operators:
Arithmetic Operators
The arithmetic operators require numeric values, and non-numeric values are converted automatically to numeric values. It Performs simple mathematical operations such as addition, Subtraction, etc.
Operator | Name | Example | Description |
+ | Addition | $a + $b | Sum of $a & $b |
– | Subtraction | $a – $b | Difference of $a & $b |
* | Multiplication | $a * $b | Product of $a & $b |
/ | Division | $a / $b | Quotient of $a & $b |
% | Modulus | $a % $b | Remainder of $a divided by $b |
** | Exponentiation | $a ** $b | $a raised to the power $y |
Example
<?php $a=20; $b=10; echo ($a+$b)."<br>"; echo ($a-$b)."<br>"; echo ($a*$b)."<br>"; echo ($a/$b)."<br>"; echo ($a%$b)."<br>"; ?>
Output
30 10 200 2 0
Logical or Relational Operators
Logical Operators help to build logical expressions. They operate with conditional statements and return boolean values, i.e., either TRUE or FALSE.
Operator | Name | Example | Description |
And | AND | $a and $b | It returns a value of TRUE only if both its operands are true. |
Or | OR | $a or $b | It returns a value of true if either of its operands is true. |
xor | XOR | $a xor $b | True if either $x or $z is real but not both |
&& | AND | $a && $b | It returns a value of TRUE if both its operand is right. |
|| | OR | $a || $b | It returns a value of true if either of its operands is true. |
! | NOT | !$a | It returns a value of true when $a is not true. |
Example
<?php $a = 50; $b = 30; if ($a == 50 and $b == 30) echo "and Success <br>"; if ($a == 50 or $b == 20) echo "or Success <br>"; if ($a == 50 xor $b == 20) echo "xor Success <br>"; if ($a == 50 && $b == 30) echo "&& Success <br>"; if ($a == 50 || $b == 20) echo "|| Success <br>"; if (!$c) echo "! Success <br>"; ?>
Output
and Success or Success xor Success && Success || Success ! Success
Comparison Operators
PHP provides a comparison operator to compare two operands. It returns, either true or false. If the comparison is correct, it returns true. Otherwise, it returns false.
Operator | Name | Example | Description |
== | Equal | $a == $b | It returns a value of true if $a is equal to $b |
=== | Identical | $a === $b | It returns a value of true if $a is equal to $b, and both are of the same type. |
!= | Not equal | $a != $b | It returns a value of true if $a is not equal to $b |
<> | Not equal | $a <> $b | It returns a value of true if $a is not equal to $b |
! == | Not identical | $a !== $b | It returns a value of true if $a is not equal to $b and both are not of the same type. |
< | Less than | $a < $b | It returns a value of true if $a is lesser than $b |
> | Greater than | $a > $b | It returns a value of true if $a is greater than $b |
>= | Greater than or equal to | $a >= $b | It returns a value of true if $a is greater than or equal to $b |
<= | Less than or equal to | $a <= $b | It returns a value of true if $a is less than or equal to $b |
Example
<?php $a = 80; $b = 50; $c = "80"; var_dump($a == $c); echo "<br>"; var_dump($a != $b); echo "<br>"; var_dump($a <> $b); echo "<br>"; var_dump($a === $c); echo "<br>"; var_dump($a !== $c); echo "<br>"; var_dump($a < $b); echo "<br>"; var_dump($a > $b); echo "<br>"; var_dump($a <= $b); echo "<br>"; var_dump($a >= $b); ?>
Output
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(false)
bool(true)
bool(false)
bool(true)
Conditional or Ternary Operators
This operator first evaluates an expression true or false and then execute one of the two given statements depending upon the result of the evaluation.
Syntax
$var = (condition)? value1 : value2;
Here condition will either true or false. The value one will be assigned to $var if the condition evaluates to True; otherwise, value two assign to it.
Operator | Name | Description |
?: | Ternary | If the condition is true? Then $x: or else $y. If the condition is true, then left, the result of the colon is accepted, otherwise the result on the right.
|
Example
<?php $a = -12; echo (ax > 0) ? 'The number is positive' : 'The number is negative'; ?>
Output
The number is negative.
Assignment Operator
It assigns a value to the variables. Operand on the left side is always a variable, and the operand on the right side can be a literal value, variable, expression, or function call that returns a value.
Operator | Name | Example | Description |
= | Assign | $a = $b | Assign the result |
+= | Add and assign | $a += $b | Adds two numbers and assign the result to the first |
-= | Subtract and assign | $a -= $b | Subtracts two numbers and assign the result to the first |
*= | Multiply and assign | $a *= $b | Multiply two numbers and assign the result to the first |
/= | Divide and assign quotient | $a /= $b | Divide two numbers and assign the result to the first |
%= | Divide and assign modulus | $a %= $b | Computes the modulus of two numbers and assign the result to the first |
Example
<?php // simple assign operator $a = 75; echo $a, "<br>"; // add then assign operator $a = 100; $a += 200; echo $a, "<br>"; // subtract then assign operator $a = 70; $a -= 10; echo $a, "<br>"; // multiply then assign operator $a = 30; $a *= 20; echo $a, "<br>"; // Divide then assign(quotient) operator $a = 100; $a /= 5; echo $a, "<br>"; // Divide then assign(remainder) operator $a = 50; $a %= 5; echo $a; ?>
Output
75
300
60
600
20
0
Array Operator
The array operators and functions act on the entire array. We can perform operations on an array using Array operators.
Operator | Name | Example | Description |
+ | Union | $a + $b | Union of $a & $b |
== | Equality | $a == $b | It returns the value of true if $a & $b have the same key/value pair. |
=== | Identity | $a === $b | It returns the value of true if $a & $b have the same key/value pair in the same order and of the same type. |
!= | Inequality | $a != $b | It returns true value if $a is not equal to $b |
<> | Inequality | $a <> $b | It returns true value if $a is not equal to $b |
!== | Non-identity | $a! = $b | It returns true value if $a is not identical to $b |
Example
<?php $a = array("a" => "Red", "b" => "Green", "c" => "Blue"); $b = array("u" => "Yellow", "v" => "Orange", "w" => "Pink"); $c = $a + $b; var_dump($c); echo"<br>"; var_dump($a == $b); echo"<br>"; var_dump($a === $b); echo"<br>"; var_dump($a != $b); echo"<br>"; var_dump($a <> $b); echo"<br>"; var_dump($a !== $b); ?>
Output
array(6) { ["a"]=> string(3) "Red" ["b"]=> string(5) "Green" ["c"]=> string(4) "Blue" ["u"]=> string(6) "Yellow" ["v"]=> string(6) "Orange" ["w"]=> string(4) "Pink" }
bool(false)
bool(false)
bool(true)
bool(true)
bool(true)
Increment/Decrement Operators
Increment (++) and decrement (-) operators give you a quick way to increase and decrease the value of a variable by 1.
Operator | Name | Description |
++$a | Pre increment | Increments $a by one , then returns $a |
$a++ | Post increment | Return $a then increments $a by one |
–$a | Pre decrement | Decrements $a by one , then returns $a |
$x– | Post decrement | Return $a then decrements $a by one |
Example
<?php $x = 2; echo 'if x = 2, ++$x First increments then prints <br>'; echo ++$x.'<br>'; $x = 2; echo 'if x = 2, $x++ First prints then increments <br>'; echo $x++.'<br>'; $x = 2; echo 'if x = 2, --$x First decrements then prints <br>'; echo --$x.'<br>'; $x = 2; echo 'if x = 2, $x-- First prints then decrements <br>'; echo $x--; ?>
Output
if x = 2, ++$x First increments then prints 3 if x = 2, $x++ First prints then increments 2 if x = 2, --$x First decrements then prints 1 if x = 2, $x-- First prints then decrements 2
String Operators
There are two operators for strings. These operators can be executed over strings.
Operator | Name | Example | Description |
. | Concatenation | $str 1 . $str2 | Concates $str1 and $str2 |
.= | Concatenation Assignment | $str1 . = $str2 | Appends $str1 to the $str2 |
Example
<?php $x = "How"; $y = "are"; $z = "you!!!"; echo $x. $y. $z, "<br>"; $x.= $y. $z; echo $x; ?>
Output
Howareyou!!!
Howareyou!!!
Spaceship Operator
PHP 7 brought a new operator called spaceship operator (<=>). It Compares two expressions. It is also called a combined comparison operator. This operator is similar to strcmp(). This operator uses integers, floats, strings, arrays, objects, etc.
- If values on either side are equal, it returns 0.
- If the value on the left side is greater, it returns 1.
- It returns -1 if the value on the right is greater.
Example
<?php $x = 50; $y = 50; $z = 25; echo $x <=> $y; echo "<br>"; echo $x <=> $z; echo "<br>"; echo $z <=> $y; echo "<br>"; // We can do the same for Strings $x = "Suman"; $y = "Hello"; echo $x <=> $y; echo "<br>"; echo $x <=> $y; echo "<br>"; echo $y <=> $x; ?>
Output
0
1
-1
1
1
-1
Execution Operator
PHP has an execution operator backticks (“). PHP executes the content of backticks as a shell command. Execution operator and shell_exec() give the same result.
Operator | Name | Example | Description |
“ | Backticks | echo `dir`; | Executes the shell command and returns the result.
In the example, it will show the directories available in the existing folder. |
Error Control Operators
PHP has one error control operator, i.e., at (@) symbol. Whenever it uses an expression, any error message will be ignored that might be generated by that expression.
Operator | Name | Example | Description |
@ | At | @file (‘non-existent file’) | File Error |
PHP Operators Precedence
The operator’s precedence decides which order the operator evaluates in an expression. Each operator is assigned a precedence. Some operators have equal precedence, e.g., the precedence of the add( +) and subtract( -) is equal. However, some operators have higher precedence than others, e.g., the precedence of the multiply operator ( *) is higher than the precedence of the add( +) and the subtract ( -) operators.
For example, x = 7 + 3 * 2; Here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first multiplied with 3*2 and then added into 7.
Operator | Name | Associativity |
clone new | Clone and new | Non-Associative |
[ | Array | Left |
** | Arithmetic | Right |
++ — ~ (int) (float) (string) (array) (object) (bool) @ | Increment / decrement and types | Right |
Instance of | Types | Non-associative |
! | logical (negation) | Right |
* / % | Arithmetic | Left |
+ – . | arithmetic and string concatenation | Left |
<< >> | bitwise (shift) | Left |
< <= > >= | Comparison | non-associative |
== != === !== <> | Comparison | non-associative |
& | bitwise AND | Left |
^ | bitwise XOR | Left |
| | bitwise OR | Left |
&& | logical AND | Left |
|| | logical OR | Left |
?: | Ternary | Left |
= += -= *= **= /= .= %= &= |= ^= <<= >>= => | Assignment | Right |
And | Logical | Left |
Xor | Logical | Left |
Or | Logical | Left |
, | many uses (comma) | Left |
Read More: PHP Strings
Conclusion
Operators are used with variables for various actions or with functions for changing previously declared values.
Operators divide into seven groups based on their purpose: arithmetic, comparison, assignment, increment or decrement, string, logical, and array.
We hope you have a better understanding of PHP Operators. Do check out our previous blogs if you are new to PHP, and don’t forget to read our further blogs!