PHP Array Operators

PHPServer Side ProgrammingProgramming

Introduction

PHP defines following set of symbols to be used as operators on array data types

SymbolExampleNameResult
+$a + $bUnionUnion of $a and $b.
==$a == $bEqualityTRUE if $a and $b have the same key/value pairs.
===$a === $bIdentityTRUE if $a and $b have the same key/value pairs in the same order and of the same types.
!=$a != $bInequalityTRUE if $a is not equal to $b.
<>$a <> $bInequalityTRUE if $a is not equal to $b.
!==$a !== $bNon-identityTRUE if $a is not identical to $b.

Union of arrays

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.

Following example shows use of define() function to define constants

Example

Live Demo

<?php
$arr1=array("phy"=>70, "che"=>80, "math"=>90);
$arr2=array("Eng"=>70, "Bio"=>80,"CompSci"=>90);
$arr3=$arr1+$arr2;
var_dump($arr3);
?>

Output

Following result will be displayed

array(6) {
["phy"]=>
int(70)
["che"]=>
int(80)
["math"]=>
int(90)
["Eng"]=>
int(70)
["Bio"]=>
int(80)
["CompSci"]=>
int(90)
}

comparison of arrays

Two arrays are said to be equal if they have same key-value pairs. Following example has an indexed array and other associative array with keys corresponding to index of elements in first. Hence both are equal

Example

 Live Demo

<?php
$arr1=array(0=>70, 2=>80, 1=>90);
$arr2=array(70,90,80);
var_dump ($arr1==$arr2);
var_dump ($arr2!=$arr1);
?>

Output

Following result will be displayed

bool(true)
bool(false)

Identity operators

Arrays are identical if and only if both of them have same set of key-value pairs and in same order

Example

 Live Demo

<?php
$arr1=array(0=>70, 1=>80, 2=>90);
$arr2=array(70,90,80);
var_dump ($arr1===$arr2);
$arr3=[70,80,90];
var_dump ($arr3===$arr1);
?>

Output

Following result will be displayed

bool(false)
bool(true)
raja
Published on 19-Sep-2020 13:29:59

Advertisements