PHP Array Operations

Jun 18, 2009 Author: Developer

As we mentioned in the PHP Basics chapter, a number of operators behave differently if their operands are arrays. For example, the addition operator + can be used to create the union of its two operands:

$a = array (1, 2, 3);
$b = array (’a’ => 1, ’b’ => 2, ’c’ => 3);
var_dump ($a + $b);

This outputs the following:

array(6) {
[0]=>
int(1)[1]=>
int(2)[2]=>
int(3)["a"]=>
int(1)["b"]=>
int(2)["c"]=>
int(3)
}

Note how the the resulting array includes all of the elements of the two original arrays, even though they have the same values; this is a result of the fact that the keys are different—if the two arrays had common elements that also share the same string keys or that have numeric keys (even if they are different), they would only appear once in the end result:

$a = array (1, 2, 3);
$b = array (’a’ => 1, 2, 3);
var_dump ($a + $b);

This results in:

array(4) {
[0]=>
int(1)[1]=>
int(2)[2]=>
int(3)["a"]=>
int(1)} 


views 2932
  1. Add New Comment