PHP array Complete example code

// Creating an array
$colorList = array("apple"=>"red",
"grass"=>"green",
"sky"=>"blue",
"night"=>"black",

"wall"=>"white");

//Display array item

echo "The sky is ".$colorList["sky"]

." and the grass is ".$colorList["grass"];

// Display array size

echo "The array size is: ".sizeof($colorList);

// Remove one element from the array

unset($colorList["sky"]);

echo "The new array size is: ".sizeof($colorList);

echo "";

// Check the existence of an element

if (isset($colorList["grass"])) echo "grass key is present";

else echo "grass key is not present";

if (isset($colorList["sky"])) echo "sky key is present";

else echo "sky key is not present";

// Display the complete array content

echo "Array before sorting:";

print_r($colorList);

// Display the complete array content after sorting

echo "Array after asort:";

print_r (asort($colorList));

echo "Array after sort:";

print_r (sort($colorList));

// Creating a multidimensional array

$myLists['colors'] = array("apple"=>"red",

"grass"=>"green",

"sky"=>"blue",

"night"=>"black",

"wall"=>"white");

$myLists['cars'] = array("BMW"=>"M6",

"Mercedes"=>"E 270 CDI",

"Lexus"=>"IS 220d",

"Mazda"=>"6",

"Toyota"=>"Avensis");

// Display an item from the array

echo "A demo item is:".$myLists['cars']['Toyota'];

// Create a new array

$colorList2[] = "red";

$colorList2[] = "green";

$colorList2[] = "blue";

$colorList2[] = "black";

$colorList2[] = "white";

// DUmp it's content

echo "Dump colorList2 with print_r:";

print_r($colorList2);

echo "Dump colorList2 with var_dump:";

var_dump($colorList2);

echo "";

// Display array elements from loop

echo "Array content:";

for ($i=0;$i<=4;$i++){

echo $colorList2[$i]."";

}

// Display array elements with foreach

echo "Array content:";

foreach ($colorList2 as $value) {

echo $value."";

}

Source From www.phpf1.com