PHP Array Operators: Manipulating Arrays in PHP

Rumman Ansari   Software Engineer   2024-07-09 10:11:08   5439  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

The PHP array operators are used to compare arrays.

Operator Name Example Result
+ Union $x + $y Union of $x and $y
== Equality $x == $y Returns true if $x and $y have the same key/value pairs
=== Identity $x === $y Returns true if $x and $y have the same key/value pairs in the same order and of the same types
!= Inequality $x != $y Returns true if $x is not equal to $y
<> Inequality $x <> $y Returns true if $x is not equal to $y
!== Non-identity $x !== $y Returns true if $x is not identical to $y

Example: + Union

Union of $x and $y

Code:


<!DOCTYPE html>
<html>
<body>

<?php
$x = array("a" => "red", "b" => "green");  
$y = array("c" => "blue", "d" => "yellow");  

print_r($x + $y); // union of $x and $y
?>  

</body>
</html>


Output:

The above code will produce the following result-


Array ( [a] => red [b] => green [c] => blue [d] => yellow )

Example: == Equality

Returns true if $x and $y have the same key/value pairs

Code:


<!DOCTYPE html>
<html>
<body>

<?php
$x = array("a" => "ram", "b" => "shyam");  
$y = array("c" => "rama", "d" => "shyma");  

var_dump($x == $y);
?>  

</body>
</html>


Output:

The above code will produce the following result-


bool(false)

Example: === Identity

Returns true if $x and $y have the same key/value pairs in the same order and of the same types

Code:


<!DOCTYPE html>
<html>
<body>

<?php
$x = array("a" => "ram", "b" => "mohon");  
$y = array("c" => "rama", "d" => "mohona");  

var_dump($x === $y);
?>  

</body>
</html>


Output:

The above code will produce the following result-


bool(false)

Example: != Inequality

Returns true if $x is not equal to $y

Code:


<!DOCTYPE html>
<html>
<body>

<?php
$x = array("a" => "red", "b" => "green");  
$y = array("c" => "blue", "d" => "yellow");  

var_dump($x != $y);
?>  

</body>
</html>


Output:

The above code will produce the following result-


bool(true)

Example: <> Inequality

Returns true if $x is not equal to $y

Code:


<!DOCTYPE html>
<html>
<body>

<?php
$x = array("a" => "red", "b" => "green");  
$y = array("c" => "blue", "d" => "yellow");  

var_dump($x <> $y);
?>  

</body>
</html>


Output:

The above code will produce the following result-


bool(true)

Example: !== Non-identity

Returns true if $x is not identical to $y

Code:


<!DOCTYPE html>
<html>
<body>

<?php
$x = array("a" => "red", "b" => "green");  
$y = array("c" => "blue", "d" => "yellow");  

var_dump($x !== $y);
?>  

</body>
</html>


Output:

The above code will produce the following result-


bool(true)