![]() |
|
PHP Array Operators. Free online PHP and MySQL Web Database Programming Tutorial... |
| Lessons | PHP Array Operators |
|
|
Union of Arrays We can form a union of two or more arrays by using the + operator, as shown below: $a = array("a" => "mango", "b" => "grapes"); $b = array("c" => "pear", "d" => "banana", "e" => "apple"); $c = $a + $b // combines the two arrays The above code declares two arrays $a and $b and then combines both of them. This combined array is stored in $c. The newly created $c array has all the items from $a and $b i.e.: $c["a"] refers to "mango", $c["b"] refers "grapes"), $c["c"] refers to pear, $c["d"] refers to "banana" and $c["e"] refers to "apple" In case there is a conflict in the index values of both the arrays, the elements of first array i.e. the array referred to by the left hand side of the + operator are taken and the elements of the second array are ignored. This is illustrated in the following example: $a = array("a" => "mango", "b" => "grapes"); $b = array("a" => "pear", "b" => "banana", "c" => "apple"); $c = $a + $b // combines the two arrays In the above example the array referred to by the $c has the following elements: $c["a"] refers to "mango", $c["b"] refers "grapes"), $c["c"] refers to "apple" Notice that the elements of $b having the similar key values are ignored. Checking the Equality 1 We can check the equality of two arrays by using the equality operator (==). It returns boolean true if both arrays have the same key / value pairs and false otherwise. Note that the order of key / value pairs does not matter. $a = array("a" => "mango", "b" => "grapes"); $b = array("b" => "grapes", "a" => "mango"); if($a == $b) //returns true Checking the Equality 2 There is another array operator called the identity operator (===), which we can use to check the equality of two arrays with respect to the order of the key / value pairs. It returns boolean true if both arrays have the same key / value pairs and in the same order, and false otherwise. $a = array("a" => "mango", "b" => "grapes"); $b = array("b" => "grapes", "a" => "mango"); if($a === $b) //returns false Even though the elements in the arrays $a and $b have the same key / value pairs, the if statement returns false, because the order of the key / value pairs in both the arrays, above, is not the same. Checking the Inequality We can check the inequality of two arrays by using != or <>. $a = array("a" => "mango", "b" => "grapes"); $b = array("b" => "grapes", "a" => "mango"); if( $a != $b) //returns false...both arrays are equal if( $a <> $b) //returns false...both arrays are equal Sometimes we need to check the non-identity of two arrays. Consider the following example: $a = array("a" => "mango", "b" => "grapes"); $b = array("b" => "grapes", "a" => "mango"); if( $a !== $b) //returns false...both arrays a equal, but not identical i.e. do not have the same order of key / value pairs.
Next: PHP Array Functions
|