An array is a list of items that can be stored in a single variable. Imagine making a list of things to do and each item is listed on its own sticky note. Before you know it your entire desk would be covered in sticky notes.
The alternative is to group these items together in to a single sticky note (array) of data that is simpler to read and easier to process.
<?php $notes = array("sticky note 1", "sticky note 2", "sticky note 3"); ?>
You can also write an array like this which is simpler to read, especially with larger arrays.
<?php $notes = array( "sticky note 1", "sticky note 2", "sticky note 3"); ?>
Viewing the Contents of an Array
Sometimes its not clear what is contained within an array or variable and so we need a way to see it in a human readable way.
Since you can’t just echo
out an array we need to use something called var_dump()
and as the name suggests, it dumps the contents of the array or variable out so we can see whats in it.
<?php $notes = array( 'sticky note 1', // [0] 'sticky note 2', // [1] 'sticky note 3'); // [2] var_dump($notes); ?>
This will dump out something like this:
array(3) { [0] => string(13) "sticky note 1" [1] => string(13) "sticky note 2" [2] => string(13) "sticky note 3" }
Accessing an Array by Offset
We can access items in an array by using []
or {}
. Each item in array is numbered starting from 0.
<?php $notes = array( "sticky note 1", // [0] "sticky note 2", // [1] "sticky note 3"); // [2] ?>
If you wanted to access “sticky note 2” you can echo out its position like so:
<?php echo $notes[1]; // outputs "sticky note 2" // or echo $notes{1}; // outputs "sticky note 2" ?>
It is more common to see []
than {}
but the choice is yours, you should simply be aware of the different syntax’s available.
Modifying Array Elements
Items within an array can have their values changed by specifying its position and providing a new value. PHP is executed top down so values can be reassigned. For example.
<?php $var = 1; $var = 2; echo $var; // outputs 2 ?>
You can change an array items value by selecting its position and assigning it a new value like so:
<?php $notes = array( "sticky note 1", // [0] "sticky note 2", // [1] "sticky note 3"); // [2] $notes[1] = "new sticky note"; echo $notes[1]; // outputs "new sticky note" ?>
Deleting Array Elements
You can remove unwanted elements in an array with unset
.
<?php $notes = array( "sticky note 1", // [0] "sticky note 2", // [1] "sticky note 3"); // [2] unset($notes[1]); ?>
This will remove “sticky note 2” from our array.
In some cases you may need to unset an entire array and you can do that by simply referencing the variable that stores the array.
<?php $notes = array( "sticky note 1", // [0] "sticky note 2", // [1] "sticky note 3"); // [2] unset($notes); ?>
Arrays are one of the most useful aspects of PHP and together with loops you can create efficient methods of handling and/or echo
‘ing out data.
Next: we will look at for and foreach loops!