PHP Operators

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

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.

  1. Unary Operators: Works on single operand such as ++, — etc.
  2. Binary Operators: Works on two operands such as +,-,*, etc.
  3. 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.

OperatorNameExampleDescription
+Addition$a + $bSum of $a & $b
Subtraction$a – $bDifference of $a & $b
*Multiplication$a * $bProduct of $a & $b
/Division$a / $bQuotient of $a & $b
%Modulus$a % $bRemainder 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.

OperatorNameExampleDescription
AndAND$a and $bIt returns a value of TRUE  only if both its operands are true.
OrOR$a or $bIt returns a value of true if either of its operands is true.
xorXOR$a xor $bTrue if either $x or $z is real but not both
&&AND$a && $bIt returns a value of TRUE if both its operand is right.
|| OR$a || $bIt returns a value of true if either of its operands is true.
!NOT!$aIt 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.

OperatorNameExampleDescription
==Equal$a == $bIt returns a value of true if $a is equal to $b
===Identical$a === $bIt returns a value of true if $a is equal to $b, and both are of the same type.
!=Not equal$a != $bIt returns a value of true if $a is not equal to $b
<>Not equal$a <> $bIt returns a value of true if $a is not equal to $b
! ==Not identical$a !== $bIt returns a value of true if $a is not equal to $b and both are not of the same type.
<Less than$a < $bIt returns a value of true if $a is lesser than $b
>Greater than$a > $bIt returns a value of true if $a is greater than $b
>=Greater than or equal to$a >= $bIt returns a value of true if $a is greater than or equal to $b
<=Less than or equal to$a <= $bIt 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.

OperatorNameDescription
?: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.

OperatorNameExampleDescription
=Assign$a = $bAssign the result
+=Add and assign$a += $bAdds two numbers and assign the result to the first
-=Subtract and assign$a -= $bSubtracts two numbers and assign the result to the first
*=Multiply and assign$a *= $bMultiply two numbers and assign the result to the first
/=Divide and assign quotient$a /= $bDivide two numbers and assign the result to the first
%=Divide and assign modulus$a %= $bComputes 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.

OperatorNameExampleDescription
+Union      $a + $bUnion of $a & $b
==Equality      $a == $bIt returns the value of true if $a & $b have the same key/value pair.
===Identity      $a === $bIt 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 != $bIt returns true value if $a is not equal to $b
<>Inequality       $a <> $bIt returns true value if $a is not equal to $b
!==Non-identity       $a! = $bIt 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.

OperatorNameDescription
++$aPre incrementIncrements $a by one , then returns $a
$a++Post incrementReturn $a then increments $a by one
–$aPre decrementDecrements $a by one , then returns $a
$x–Post decrementReturn $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.

OperatorNameExampleDescription
.Concatenation     $str 1 . $str2Concates $str1 and $str2
  .=Concatenation Assignment      $str1 . = $str2Appends $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.

OperatorNameExampleDescription
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.

OperatorNameExampleDescription
@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.

OperatorNameAssociativity
clone newClone and newNon-Associative
[ArrayLeft
**ArithmeticRight
++ — ~ (int) (float) (string) (array) (object) (bool) @Increment / decrement and typesRight
Instance ofTypesNon-associative
!logical (negation)Right
* / %ArithmeticLeft
+ – .arithmetic and string concatenationLeft
<< >>bitwise (shift)Left
< <= > >=Comparisonnon-associative
== != === !== <>Comparisonnon-associative
&bitwise ANDLeft
^bitwise XORLeft
|bitwise ORLeft
&&logical ANDLeft
||logical ORLeft
?:TernaryLeft
= += -= *= **= /= .= %= &= |= ^= <<= >>= =>AssignmentRight
AndLogicalLeft
XorLogicalLeft
OrLogicalLeft
,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!

Leave a Reply

Your email address will not be published. Required fields are marked *