skahan
8/21/2013 - 10:40 PM

Basic Array

Basic Array

<?php
$imempty = array()//Defines empty array
?>

<?php
$numbers = array(4,8,15,16,23,42);//Defines array with values
//To access array values, use value's position in square brackets:

echo $numbers[1];//8 - note: first position of array is 0, not 1 (which is 
//why this example returns 8 instead of 4).
?>

<?php
//Arrays can be mixed. The same array can contain a integer, a string, and another array:
$mixed = array(6,"fox","dog",array("x","y","z"));
echo $mixed[2];//dog;
//To access a value in a nested array:
echo $mixed[3][1];//y
?>

<?php
//To add to an array at any position:
$mixed = array(6,"fox","dog",array("x","y","z"));
$mixed[2] = "cat";//This will REPLACE dog, it won't insert new value.
print_r($mixed);//Array ( [0] => 6 [1] => fox [2] => cat [3] => Array ( [0] => x [1] => y [2] => z ) )
$mixed[4] = "rabbit";
print_r($mixed);//Array ( [0] => 6 [1] => fox [2] => cat [3] => Array ( [0] => x [1] => y [2] => z ) [4] => rabbit )

//You can add to the end of an array without specifying a position by leaving the index blank when assinging:
$mixed[] = "elephant";
print_r($mixed);//Array ( [0] => 6 [1] => fox [2] => cat [3] => Array ( [0] => x [1] => y [2] => z ) [4] => rabbit [5] => elephant )

?>