PHP Arrays
Defining an array is done the following way
$myarray = array();
filling it is done like this:
$myarray[0]=”first value”;
$myarray[] .= “second value”; // automatically added as next array spot
sometimes, we need to fill in several elements at once, just pass the elements the array function:
$myarray=array(“value one”,”value 2”, “value 3”,”value 4”);
arrays don’t have to be indexed on numbers, they can be associative. Associative arrays are similar to a dictionary where you look up a word and get the associated definition… in here, you enter a key (word) and you get its value (definition).
$myarray=array();
$myarray[“www”]=”world wide web”;
$myarray[“http”]=”Hypertext Transfer Protocol”;
$myarray[“tcp”]=”transfer control protocol”;
echo(“Definition for www is” . $myarray[“www”]);
sometimes, it is useful to know if an array has been set… you do this by using the isset fonction.
isset($myarray[“www”]) -> is true in the previous example
isset($myarray[“computer”] ) -> is false in the previous example, it’s not assigned
in cases where array indices are sequential, it is not necessary to specify each array index. For example:
$myArray[5]=1;
$myArray[]=6654;
$myArray[]="hello”;
Will result with the following array: array([5]=>1, [6]=>6654,[7]=>"hello")
Please note that any array element can be itself an array. For example:
$myArray=array(array(1,2,3,4),array(“apples”, “oranges”, “trees”), “mixed_array”=>array(“mixed”,”array”,123,);
As you can see, array contents can be of any variable type and assigned any associative key if needed… though if it will be used with a foreach statement, indices are not necessary and will default to sequential ordering, starting with 0.