Wednesday, March 28, 2007

PHP: Array

Operators. Suppose you need to compare two arrays,

$a = array( 1, 2, 3 ); $b = array( 0 => 1, 2 => 3, 1 => 2 ); var_dump( $a == $b ); // will print bool(true) var_dump( $a == $b ); // will print bool(true) var_dump( $a === $b ); // will print bool(false)
The identity operator "===", however, does care about the order. Array also support union of set operator. However the union operation is based on key:
$arrA = array( 1, 2 ); $arrB = array( 3, 4 ); var_dump( $arrA + $arrB ); // Since both arrays are using default key, 0 and 1, // no element from $arrB will be added to the union // array(2) { // [0] => int(1) // [1] => int(2) // } $arrC = array( 1, 2 ); $arrD = array( 'a' => 1, 'b' => 2 ); var_dump( $arrC + $arrD ); // However, this will print // array(4) { // [0] => int(1) // [1] => int(2) // ["a"] => int(1) // ["b"] => int(2) // }
Iteration. Everyone probably familiar with array iteration using while and each.
$arr = array( 'a', 'b', 'c' ); // longer version of while( $arr as $key => $val ) { while( list($key, $val) = each($arr) ) { print "$key : $val" . PHP_EOL; } // will print // 0 : a // 1 : b // 2 : c
You can also use array pointer. For example
$arr = array( 'a'=>'a', 'b'=>'b', 'c'=>'c' ); reset($arr); while( key($arr) != null ) { print key($arr) . " : " . current($arr) . PHP_EOL; next($arr); } // will print // a : a // b : b // c : c
However, you need to careful using 0 or '0' for key which will cause key($arr) != null be false and will not go through the loop. Remember the default key for array is 0.

No comments: