Declare and Build an array |
1. Declare a variable; $mobile_phones 2. Assign variable to an array; $mobile_phones= array ("Sony", "Nokia", "Samsung", "HTC", " ZTE") 0 1 2 3 4 Remember that array value starts at 0. 3. Call out the array Echo $mobile_phones; // this will echo all values in $mobile_phones If you want to call out Samsung, you need to echo Echo $mobile_phones[2]; |
Associative Array |
$book = [
'title' => "Sherlock Holmes", 'author' => "Arthur Conan Doyle", 'description' => " a fictional private detective." ]; echo $book[title] ." was written by " .$book[author]. ". It's ".$book[description]; You should see something like Sherlock Holmes was written by Arthur Conan Doyle. It's a fictional private detective. |
Index Array
Output should be
|
The only difference between Associative Array and Index Array is instead of having echo, Index Array has print_r
$planets=array('Mars', 'Jupiter', 'Saturn'); print_r($planets); You should see Array ( [0] => Mars [1] => Jupiter [2] => Saturn ) appear on your screen. $planets = [
'Sun ', 'Moon ', 'Venus ', ]; foreach ($planets as $name): echo "<li> $name </li>"; endforeach; <html>
<head> <title> Welcome </title> </head> <body> <ul> <?php $planets = [ 'Uranus', 'Venus', 'Mercury', 'Mars']; foreach ($planets as $milkyWay) echo "<li>$milkyWay</li>"; ?> </ul> |
Accessing ArrayYou can access arrays through using a foreach loop
The code to your right should produce
Foreach loop also works with associative arrays.You should see something like this on your screen:
Sun glows during the day. Moon glows at night. Venus can be seen just before sunrise. |
$planets = [
'Sun' => 'glows during the day', 'Moon' => 'glows at night', 'Venus'=> 'can be seen just before sunrise' ]; foreach ($planets as $key => $value) { echo "<p> $key $value. </p>"; } |