An array is a collection of multiple values or ‘compartments’ stored in one variable. Arrays can be used to sort, group, count data and make it available to the front end user.
Building an array
For example, lets say we wanted to build an array of our favourite garden plants:
Plants: Begonia, Marigold, Impatient, Nasturtium
The ‘Plants’ data has many parts and can be put into an array using the following PHP:
<?php
$plants = array(”Begonia”, “Marigold”, “Impatient”, “Nasturtium”);
?>
Showing your data
Simply echoing out an array will not work as it is a variable of many parts. you need to be more specific:
<?php
$plants = array(”Begonia”, “Marigold”, “Impatient”, “Nasturtium”);
print_r($plants);
?>
This will display:
Array ( [0] => Begonia [1] => Marigold [2] => Impatient [3] => Nasturtium )
As you can see from the above, the array is presented with each item with an number (it can be alpha-numeric) or ‘key’ next to each plant name or ‘value’. Obviously, this list is not a pretty one, but helpful all the same.
You can echo out a single value from your array by using the following:
<?php
$plants = array(”Begonia”, “Marigold”, “Impatient”, “Nasturtium”);
echo $plants[2];
?>
This will echo out to your browser as:
Impatient
Remember, the first key (if numeric) will be by default zero.
Looping through your array with FOREACH
If you would like to echo out the contents of your array, you can use a foreach statement.
<?php
$plants = array(”Begonia”, “Marigold”, “Impatient”, “Nasturtium”);
echo “<ol>”;
foreach($plants as $flower)
{
echo “<li>$flower</li>”;
}
echo “</ol>”;
?>
This will echo out:
- Begonia
- Marigold
- Impatient
- Nasturtium
Looping with a WHILE Loop
While loops work in a similar way to foreach in that it can loop through parts of your array to echo out content. The main difference being that you can be more specific on the ‘count’ or amount of times you loop through your data.
<?php
$plants = array(”Begonia”, “Marigold”, “Impatient”, “Nasturtium”);
echo “<ol>”;
$i = 0;
while ( $i <= count($plants)-1 )
{
echo “<LI>”.$plants[$i];
$i++;
}
echo “</ol>”;
?>
Count() can be a very useful function for not only fixing how many loops are required, but also for counting the content of you array:
<?php
$plants = array(”Begonia”, “Marigold”, “Impatient”, “Nasturtium”);
echo “You have “.count($plants);
echo “<ol>”;
$i = 0;
while ( $i <= count($plants)-1 )
{
echo “<LI>”.$plants[$i];
$i++;
}
echo “</ol>”;
?>
Sorting, grouping and filtering arrays
Here are a few other things you can do with arrays.
- Remove duplicate values (grouping): $clean = array_unique($dirty);
- Filter out empty values: $array = preg_grep(’#\S#’, array_map(’trim’, $array));
- Shuffle (randomise) array: shuffle($array);
A comprehensive list of array functions can be found at: http://php.net/manual/en/function.in-array.php
