×
☰ See All Chapters

PHP Operators

An operator is something that performs some action on one or more values and yields another value. Variables which hold the value are called operands. Operator together with operands forms an expression.

Operator Types

  • Null Coalescing operator (??) 

  • Spaceship Operator (<=>) 

  • Execution Operator (``) 

  • Incrementing (++) and Decrementing (--) Operators 

  • String Operators (. and .=) 

  • Object and Class Operators 

  • Assignment Operator 

  • Arithmetic Operators 

  • Comparison Operators 

  • Logical Operators (&&/AND and ||/OR) 

  • Conditional Operators  (?) 

  • Bitwise Operators 

  • instanceof (type operator) 

Null Coalescing Operator (??)

This operator is introduced in PHP 7. This operator returns its first operand if it is set and not NULL. Otherwise it will return its second operand.

Example:

<?php

$mango = "Mango";

$fruit = $mango ?? 'Apple';

echo $fruit; // Prints Mango

?>

<?php

//$mango = "Mango";

$fruit = $mango ?? 'Apple';

echo $fruit; // Prints Apple

?>

The above code can be written without using Null Coalescing Operator (??) as below:

<?php

$mango = "Mango";

if (isset($mango)) {

    $fruit = $mango;

} else {

    $fruit = 'Apple';

}

?>

Null Coalescing Operator (??) can also be chained with multiple operands as below:

<?php

$mango = "Mango";

$banana = "Banana";

$fruit = $mango ?? $banana ?? 'Apple';

echo $fruit; // Printe Apple

?>

When using Null coalescing operator on string concatenation you should use parentheses () as below:

<?php

$firstName = "Manu";

$lastName = "Manjunatha";

//$fullName = $firstName ?? "Manu" . " " . $lastName ?? "Manjunatha"; --> This is wrong

$fullName =  ($firstName ?? "Manu") . " " . ($lastName ?? "Manjunatha");

?>

Spaceship Operator (<=>)

This operator is introduced in PHP 7. This operator will return -1, 0 or 1 if the first expression is less than, equal to, or greater than the second expression.  Both expressions should be evaluated to value of same type. If values are not comparable then it gives an undefined behavior.

<?php

// Integers

echo (10 <=> 10); // 0

echo (15 <=> 16); // -1

echo (18 <=> 11); // 1

// Floats

echo (11.5 <=> 11.5); // 0

echo (11.5 <=> 12.5); // -1

echo (12.5 <=> 11.5); // 1

// Strings

echo ("x" <=> "x"); // 0

echo ("x" <=> "y"); // -1

echo ("y" <=> "x"); // 1

?>

Execution Operator (``)

PHP backticks (``) execution operator is used to run shell commands. Output of the command will be returned after execution. Below example run the “dir” command on windows operating system which list out all the files in the folder.

<?php

$output = `dir`;

echo "<pre>$output</pre>";

?>

php-operators-0
 

Same “dir” command when executed from command prompt :

php-operators-1
 

Incrementing (++) and Decrementing (--) Operators

  • The increment operator ++ adds one to a number, and the decrement operator – – subtracts one from a variable. 

  • The two operators are applied as either a prefix or a suffix to any variable that represents a number. 

  • Using these operators as a prefix is referred to as pre increment. 

  • Using these operators as a suffix to a variable is referred to post increment. 

++var

Increment and use. Increment the variable by 1 before it is used

var++

Use and Increment. Use the value first and then increment the value by 1

--var

Decrement and use. Decrement the variable by 1 before it is used

var--

Use and Decrement. Use the value first and then Decrement the value by 1

 

<?php

$x = 10;

echo $x; // Prints 10

// Pre-increment operator increments $x by one, then returns $x

echo ++$x; // Prints 11

// Pre-decrement operator decrements $x by one, then returns $x

echo --$x; // Prints 10

// Post-increment operator returns $x, then increments $x by one

echo $x++; // Prints 10 (but $x value is now 11)

// Post-decrement operator returns $x, then decrements $x by one

echo $x--; // Prints 11 (but $x value is now 10)

?>

String Operators (. and .=)

There are two string operators. The first is the concatenation operator ('.'), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator ('.='), which appends the argument on the right side to the argument on the left side.

<?php

$a = "Hello ";

$b = $a . "World!";

echo $a."</br>";

 

$x = "Hello ";

$x .= "World!";

echo $x;

?>

php-operators-2
 

Object and Class Operators

  • Members of objects or classes can be accessed using the object operator (->) and the class operator (::). 

  • If members are non-static, then members can be accessed through object reference using object operator (->). Below is the syntax to access non-static through object reference using object operator (->). 

$object_reference_name->member_name;

Note that after the object operator, the $ should not be written $object_reference->memberName instead of $object_reference->$memberName).

You can also access static members using object operator (->), but syntax remain the same.

  • If members are static or if members are constants, then members can be accessed using class operator (::). No need to create object and have object reference to access static members or constant members. Below is the syntax of class operator (::). 

ClassName::$static_member_Name;

ClassName::constant_member_Name;

$ should not be used for constant members and should not be used for static members.

Object and Class Operators Example

<?php

class HelloClass {

    public $non_static_variable = 10;

    public static $static_variable = 20;

    const CONSTANT_VARIABLE = 30;

    public function nonStaticFunction() { return 40; }

    public static function staticFunction() { return 50; }

}

$object = new HelloClass();

var_dump($object->non_static_variable); // int(10)

var_dump($object::$static_variable); // int(20)

var_dump($object::CONSTANT_VARIABLE); // int(30)

var_dump(HelloClass::$static_variable); // int(20)

var_dump(HelloClass::CONSTANT_VARIABLE); // int(30)

var_dump($object->nonStaticFunction()); // int(40)

var_dump($object::nonStaticFunction()); // int(40)

var_dump(HelloClass::staticFunction()); // int(50)

$classname = "HelloClass";

var_dump($classname::staticFunction()); // also works! int(50)

?>

Object and Class operators have left associativity, which can be used for 'chaining':

<?php

class A {

    public function getB() { return new B(); }

}

 

class B {

    public function sayHi() { echo "Hi"; }

}

 

$a = new A();

$a ->getB() ->sayHi();

?>

Assignment Operators

It has this general form:

variable = expression;

Here, the type of variable must be compatible with the type of expression.

There are following assignment operators supported by java language:

Operator

Description

Example

=

Simple assignment, Assigns values from right side operands to the left side operand

K = M+N will assign value f  M+N to K

+=

Add AND assignment. It adds right operand to the left operand and assigns the result to left operand.

M+=N is equivalent to M = M+N

-=

Subtract and assignment. It subtracts right operand from the left operand and assigns the result to left operand.

M-=N is equivalent to M = M-N

*=

Multiply AND assignment. It multiplies right operand to the left operand and assigns the result to left operand.

M*=N is equivalent to M = M*N

/=

Divide AND assignment. It divides right operand from the left operand and assigns the result to left operand.

M/=N is equivalent to M = M/N

%=

Modulus AND assignment. It takes modulus of two operands and assigns result to the left operand.

M%=N is equivalent to M = M%N

.=

Combined concatenation and assignment of a string

M.=N is equivalent to M = M.N

<<=

Left shift AND assignment

M<<=N is equivalent to M = M<<N

>>=

Right shift AND assignment

M>>=N is equivalent to M = M>>N

&=

Bitwise AND assignment

M&=N is equivalent to M = M&N

^=

Bitwise exclusive OR  and assignment

M^=N is equivalent to M = M^N

|=

Bitwise inclusive OR  and assignment

M|=N is equivalent to M = M|N

Arithmetic Operators

Assume variable M holds 10 and variable N holds 20, then:

Operator

Description

Example

+

Add

M+N will give 30

-

Subtract

M-M will give -10

*

Multiplies both operands

M*N will give 200

/

Divides numerator by de-numerator

M/N will give 2

%

Remainder after an integer division

M%N will give 0

Comparison Operators

The comparison operators are used to compare two values. The outcome of these operators is a boolean value.

Operator

Name

Example

Result

==

Equal

$m == $n

True if $m is equal to $n

===

Identical

$m === $n

True if $m is equal to $n, and they are of the same type

!=

Not equal

$m != $n

True if $m is not equal to $n

<>

Not equal

$m <> $n

True if $m is not equal to $n

!==

Not identical

$m !== $n

True if $m is not equal to $n, or they are not of the same type

<

Less than

$m < $n

True if $m is less than $n

>

Greater than

$m > $n

True if $m is greater than $n

>=

Greater than or equal to

$m >= $n

True if $m is greater than or equal to $n

<=

Less than or equal to

$m <= $n

True if $m is less than or equal to $n

Logical Operators (&&/AND and ||/OR)

The logical operators are typically used to combine conditional statements.

Operator

Example

Result

and

$m and $n

True if both $m and $n are true

or

$m or $n

True if either $m or $n is true

xor

$m xor $n

True if either $m or $n is true, but not both

&&

$m && $n

True if both $m and $n are true

||

$m || $n

True if either $m or $n is true

!

!$m

True if $m is not true

Note that the && and || operators have higher precedence than and and or. It’s safer to use && and || instead of and and or. See table below:

Evaluation

Result of $e

Evaluated as

$e = false || true

true

$e = (false || true)

$e = false or true

false

($e = false) or true

Conditional Operators (?)

It is called the ternary operator because it has three operands, and it is basically a shortcut mechanism for writing an if/else control structure. The syntax is the following:

(expr1) ? expr2 : expr3

If the expr1 is true, the expr2 statement is executed. If the expr2 is false, then expr3 statement is executed.

It is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

?: is often referred to as Elvis operator.

This behaves like the Null Coalescing operator ??, except that ?? requires the left operand to be exactly null while ?: tries to resolve the left operand into a boolean and check if it resolves to boolean false.

Bitwise Operators

The bitwise operators are used to perform bit-level operations on operands. These operators allow the evaluation and manipulation of specific bits within the integer.

Operator

Name

Example

Result

&

And

$a & $b

Bits that are 1 in both $a and $b are set to 1, otherwise 0.

|

Or (Inclusive or)

$a | $b

Bits that are 1 in either $a or $b are set to 1

^

Xor (Exclusive or)

$a ^ $b

Bits that are 1 in either $a or $b are set to 0.

~

Not

~$a

Bits that are 1 set to 0 and bits that are 0 are set to 1

<<

Shift left

$a << $b

Left shift the bits of operand $a $b steps

>>

Shift right

$a >> $b

Right shift the bits of $a operand by $b number of places

instanceof (type operator)

instanceof operator is used to check if some object is of a certain class. Below is the syntax of instanceof operator.

$result = $object_refernce instanceof ClassName;

The first operand (left) must be an object. Operand should not be any constant, string, integer, boolean, float, character.

The second operand (right) parameter is the class to compare with. The class can be provided as the class name itself, a string variable containing the class name (not a string constant!) or an object of that class.

<?php

class MyClass {

}

$o1 = new MyClass();

$o2 = new MyClass();

$name = 'MyClass';

// in the cases below, $a gets boolean value true

$a = $o1 instanceof MyClass;

$a = $o1 instanceof $name;

$a = $o1 instanceof $o2;

// counter examples:

$b = 'b';

$a = $o1 instanceof 'MyClass'; // parse error: constant not allowed

$a = false instanceof MyClass; // fatal error: constant not allowed

$a = $b instanceof MyClass; // false ($b is not an object)

?>

When you have a class hierarch where class extends other class, instanceof can also be used to check whether an object is of some class which extends another class or implements some interface.

<?php

 

interface Colour

{

}

 

class Red implements Colour

{

}

 

class Salmon extends Red

{

}

 

$o = new Salmon();

$a = $o instanceof Salmon;

$a = $o instanceof Red;

$a = $o instanceof Colour;

?>

 


All Chapters
Author