What is an array?
An array is a list of a certain variable type, where each item in the list can be referenced by a unique index number, usually starting at 0. Think about it in real terms as you might think about a shopping list. EG:
Now imagine that you had one variable to hold them all:
And each item in the list, had an identifier linked with the one variable:
0 = Cheese
1 = Eggs
2 = Milk
3 = Bread
In PHP this would look like this:
$Shopping-list = "Cheese";
$Shopping-list = "Eggs";
$Shopping-list = "Milk";
$Shopping-list = "Bread";
As you can see from above what we actually have is a list of strings, and we can do exactly the same with numbers:
$numbers = 21;
$numbers = 50;
$numbers = 43;
Like any other variable type, PHP will automatically define a variable type and set it up for you when you start using it, however in most cases (and it’s good practice) you should usually pre-declare your intention to use an array, especially if you don’t know in advance what your going to be storing in it. You can do this by using the following PHP function.
$myArray = array();
This will declare an empty array called “
myArray” ready to start accepting additions.
To add items to it, you can use the null index format, which will then add the new item at the next available free index:
$myArray = "Hello"; $myArray = "World";
This will allocate “hello” to slot 0, and “world” to slot 1. You can delete an element at an index by using the unset function:
We’ll leave only
$myArraycontaining “hello”. A word of warning though, using unset DOES NOT reorder the indexes, I’ve lost count of how many times this has bitten me in a program, only to examine an array’s contents and find holes in the indexes, so always be sure your code is ready and able to detect a gap in an array if your going to do this.
A better way to remove elements is to use the “
array_splice" function, simply by giving it the index to remove and a length of 1 as follows:
We’ll remove element number 1 and then reorder the indexes, try the following to see what I mean:
$myArray = array("one","two","three","four"); print_r($myArray); array_splice($myArray,1,1); print_r($myArray);
You’ll see that “two” gets removed and the indexes reordered to close the hole, also if you want to keep a copy of the removed elements in another array, you can assign a variable to the result of the function, and the deleted elements will be stored in it, eg:
$deleted = array_splice($myArray,1,1);