Arrays can be extremely useful. It's just when someone asks in what instance would you use an array, I end up being quite stumped to give a decent example. The truth is that arrays are used everywhere, from returning information from a database table, or storing models for your code. They come in a few forms: basic arrays or numeric arrays, multidimensional arrays and associate arrays.
In its most basic form, an array can be thought of as a collection of related (or sometimes unrelated) values. For example, if I had a collection of fruit I could store them in an array like this:
PHP Code:
$aFruits = array('Apples', 'Pears', 'Oranges');
Then I could access those 3 items fairly easy. Arrays, by default, begin at index 0. That is, to echo out
Apples I could reference it like so:
PHP Code:
echo $aFruits[0];
PHP then counts up from 0 and goes on indefinitely. We have 3 elements in our arrays: 0, 1 and 2, storing
Apples,
Pears and
Oranges, respectively. This is all pretty basic stuff.
There are an abundance of array functions that PHP has straight out of the box. Although there are too many to mention in one article, a few key array functions you may wish to familiarise yourself with:
- array_key_exists() : Checks to see if the key specified exists in the specified array. In our array above, 2 is a valid key, but 3 is not.
- array_merge() : Combines one array with another array. For example, we could merge our fruit array with a member array. This would create one larg array containing both fruits and members.
- array_push() : Push an element onto the end of our array.
- array_pop() : Removes the element key from our array. So in our example, oranges would disappear from our array and leave us with 2 remaining elements, Pears and Apples.
- array_shift() : Removes the first element from our array. So in our example, apples would disappear from our array, leaving us left with Pears and Oranges.
- array_unique() : Removes all duplicate elements from an array.
- array_unshift() : Push an element onto the beginning of our array.
Let me mention a few of these functions, the ones you are likely to use if you are a beginner to PHP.
Push
PHP Code:
$aFruits = array('Apples', 'Pears', 'Oranges');
array_push($aFruits, 'Kiwi');
Result: Pushes the value
Kiwi onto the end of our array.
Unshift
PHP Code:
$aFruits = array('Apples', 'Pears', 'Oranges');
array_unshift($aFruits, 'Kiwi');
Result: Pushes the value
Kiwi onto the beginning of our array.
Pop
PHP Code:
$aFruits = array('Apples', 'Pears', 'Oranges');
array_pop($aFruits);
Result: Removes
Oranges from our array.
Shift
PHP Code:
$aFruits = array('Apples', 'Pears', 'Oranges');
array_shift($aFruits);
Result: Removes
Apples from our array.