PHP - Getting Started with Arrays

by
Jeremy Canfield |
Updated: February 16 2022
| PHP articles
Following are both valid examples of how to create an empty array (does not contain any values).
$foo = [];
$foo = array();
In this example, an array named fruit contains different types of fruit.
$fruit = array("apple", "banana", "orange", "grapes");
var_dump can be used to print the data structure of the array.
var_dump($fruit);
Which will return the following. Notice that integers 0 1 2 3 are used as the key for each value in the array. If you want, you can define the keys.
array(4) { [0]=> string(5) "apple" [1]=> string(6) "banana" [2]=> string(6) "orange" [3]=> string(6) "grapes" }
Or print_r can be used.
print_r ($file);
Which should return something like this.
Array ( [0] => apple [1] => banana [2] => orange [3] => grapes )
Specific elements can be printed, like this.
echo "fruit[0] = " . $fruit[0] . "<br />";
echo "fruit[1] = " . $fruit[1] . "<br />";
echo "fruit[2] = " . $fruit[2] . "<br />";
echo "fruit[3] = " . $fruit[3] . "<br />";
Which will return the following.
fruit[0] = apple
fruit[1] = banana
fruit[2] = orange
fruit[3] = grapes
Or you can loop through the array.
foreach ($fruit as $value) {
echo "$value<br \>";
}
Which will return the following.
apple
banana
orange
grapes
Did you find this article helpful?
If so, consider buying me a coffee over at