Created
June 1, 2016 09:46
-
-
Save ryesalvador/e701d3ca472e39f963ef8257c7d5df01 to your computer and use it in GitHub Desktop.
Creating an array in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* Adding items in an array implicitly. */ | |
$junk[] = "hamburger"; | |
$junk[] = "snack foods"; //This doesn't get displayed. | |
$junk[] = "pizza"; | |
$junk[] = "carbonated beverage"; | |
/* Adding items in an array explicitly. */ | |
$junk[6] = "tacos"; | |
$junk[7] = "gum"; | |
$junk[8] = "candy"; | |
$junk[1] = "potato chips"; //This reassigns a new value to line 5. | |
echo "<strong>An array of junk foods:</strong><br>"; | |
print_r($junk); //A function to display information in human-readable form. | |
/* We can also create arrays using the array keyword. */ | |
$foods = array("fruits", "vegetables", "proteins", "grains", "dairy"); | |
echo "<br><br><strong>An array of food groups: </strong><br>"; | |
print_r($foods); | |
/* PHP allows an array of key and value pairs known as associative arrays. */ | |
$examples = array('fruit' => "coconut", | |
'vegetable' => "potato", | |
'protein' => "eggs", | |
'grains' => "rice"); | |
$examples['dairy'] = "butter"; //Assignment by name. | |
/* Traversing through the array using the foreach...as. */ | |
echo "<br><br><strong>An array of examples for each food group: </strong><br>"; | |
foreach($examples as $group => $food) | |
echo "$group:\t$food<br>"; | |
echo "<br><strong>A question:</strong><br>"; | |
echo "How do you like your " | |
. $examples['protein'] . "?<br>"; // An example of referencing an item by name. | |
/* Here is an example of a multidimensional array. | |
* We can create as many dimensions as we like. */ | |
$groceries = array('fruits' => array( | |
'apple' => "red apple", | |
'banana' => "ripe banana", | |
'mango' => "green mango"), | |
'vegetables' => array( | |
'eggplant' => "omelette", | |
'broccoli' => "steamed", | |
'carrot' => "raw"), | |
'proteins' => array( | |
'fish' => "fillet", | |
'beef' => "roasted", | |
'chicken' => "fried"), | |
'dairy' => array( | |
'milk' => "skimmed", | |
'yogurt' => "frozen", | |
'cheese' => "Parmesan")); | |
echo "<br><strong>More examples:</strong><br>"; | |
foreach($groceries as $group => $names) | |
foreach($names as $food => $description) | |
echo "$group:\t$food\t- $description<br>"; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment