PHP Arrays
The PHP manual refers to arrays as maps with keys, this refers to the internal structure which is quite unlike that implied by the C/C++ model. In a conventional programming language an array can be thought of as a simple collection of objects laid out in memory one after the other with individual objects referred to as object[0], object[1], etc.
- Numeric Array: An array with a numeric ID key.
- Associative Array: An array where each ID key is associated with a value.
- Multidimensional Array: An array containing one or more arrays.
NOTE PHP’s numerically indexed arrays begin with position 0, not 1.
Numeric arrays
// Method I
// ========
$name = array( 'Mike','Scott','Peter' );
// Method II
// =========
$name[] = 'Mike';
$name[] = 'Scott';
$name[] = 'Peter';
// Method III
// ==========
$name[1] = 'Mike';
$name[2] = 'Scott';
$name[4] = 'Peter';
Example
<?
print "looping through array";
$x = array(0,1,4,9,16,25,36,49,64,81);
for($j = 0;$j<10; $j++)
{
print " $j : $x[$j]";
}
?>
Associative Array
<?
$mdays = array (
"January" => 31,
"February" => 28,
"March" => 31,
"April" => 30,
"May" => 31,
"June" => 30,
"July" => 31,
"August" => 31,
"September" => 30,
"October" => 31,
"November" => 30,
"December" => 31
);
print $mname . " has " . $mdays[$mname] . " days";
?>