Arrays in PHP
There are three types of arrays in PHP:
- Indexed array
- Associative array
- Multidimensional array
Example: Simple One Dimensional, Indexed PHP Array
Array elements in this type of array are accessed through a numeric key, e.g. 0, 1, etc.
<?php
$artists = array("Elton John", "Eric Clapton", "Sam Cooke", "Prince");
echo "<p>My favorite artist is " . $artists[3] . "</p>.";
?>
Output:
My favorite artist is Prince
Example: Output One Dimensional, Indexed PHP Array with Loop
<?php
$artists = array("Elton John", "Eric Clapton", "Sam Cooke", "Prince");
echo "<p>My favorite artists are: </p>";
echo "<ul>";
for ($x=0; $x < count($artists); $x++)
echo "<li>" . $artists[$x];
echo "</ul>";
?>
Output:
My favorite artists are:
- Elton John
- Eric Clapton
- Sam Cooke
- Prince
Example: Output One Dimensional, Indexed PHP Array with Loop
$employees[0] = "Mary Smith";
$employees[1] = "John Thomas";
$employees[2] = "Anne Bolton";
echo "<ul>";
for ($x=0; $x < count($employees); $x++)
echo "<li>" . $employees[$x];
echo "</ul>";
Output:
- Mary Smith
- John Thomas
- Anne Bolton
Example: PHP Associative Array
$employees["Mary Smith"] = "Programmer";
$employees["John Thomas"] = "Manager";
$employees["Anne Bolton"] = "Director";
echo "<p>Mary Smith is a " . $employees["Mary Smith"] . ".</p>";
Output:
Mary Smith is a Programmer.