Showing posts with label Array. Show all posts
Showing posts with label Array. Show all posts

Wednesday, June 6, 2007

PHP: Arrays of Arrays

Creating array of arrays

$AoA = array( array( 1, 2 ), array( 3, 4) ); print_r($AoA); // will print: // Array // ( // [0] => Array // ( // [0] => 1 // [1] => 2 // ) // // [1] => Array // ( // [0] => 3 // [1] => 4 // ) // )
Accessing array of arrays using index
for( $i=0; $i<count($AoA); $i++) { for( $j=0; $j<count($AoA[$i]); $j++) { print( $AoA[$i][$j] . "\t" ); } print("\n"); } // will print: // 1 2 // 3 4
Accessing array of arrays method 2
foreach( $AoA as $row ) { foreach( $row as $cell ) { print( $cell . "\t" ); } print("\n"); } // will print: // 1 2 // 3 4

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.