There are two kinds of Array: Regular array(based on numeric index) and Associative array(Map collection in Java); In PHP, the size of array can grow - it's loosely.
To initialize an array, use one of the fallowing:
>> $cities = array("denpasar","manila","sydney");
or
>> $cities = array();
>> $cities[] = "denpasar";
>> $cities[] = "manila";
>> $cities[] = "sydney";
or
>> $names = array("steve"=>"jobs",
>> "larry"=>"page",
>> "sergey"=>"brin");
or
>> $names = array();
>> $names["steve"] = "jobs";
>> $names["larry"] = "page";
To get to know how many elements in an array, use:
>> $count = count($cities) // return 3
To print out the structure of array use one either of:
>> print_r($cities);
>> var_dump($cities);
To make a new assoc array based on two regular array, use: $fname as key and $lname as value
>> $newAssocArray = array_combine($fname,$lname);
To get key as an array from an assoc array, use:
>> $keyArray = array_keys($names);
// result array("steve","larry","sergey")
// result array("steve","larry","sergey")
To get value as an array from an assoc array, use:
>> $valueArray = array_values($names);
// result array("jobs","page","bin")
// result array("jobs","page","bin")
To reverse the array elements order, use:
>> array_reverse($cities);
To sort an assoc arrays based on keys:
>> ksort($names);
To bind the elements of array to variables, use:
>> list($a,$b,$c) = $cities;
For iterating through elements of array, use:
>> foreach($cities as $values){
>> echo "$values <br>"
>> }
or
>> foreach($names as $keys=>$values){
>> echo "$keys: $values <br>"
>> }
No comments:
Post a Comment