Ok, even some developers who already understand php a little are always confused about arrays and don’t really know how to use them. In this lessons, we will try to cover the basic uses of Arrays in PHP.
When you declare a variable, it can only hold one value. Like the example below:
<?php $my_variable = "This is some text"; ?>
As you can see, it can only store “This is some text”, or a single value. But what if you have to store multiple values which have some relationship between them? Let’s take an example from the previous lesson, remember our guy named John? We declared his age. Let’s say we want to add his name, location etc. We can do it like this:
$persons_age = ’16’;
$persons_name = ‘John’;
$persons_location = ‘California’;
But with the use of arrays, you can store all of that information in one variable. Like below:
<?php $persons = array('John','16','California'); ?>
Later in this chapter, we will have a closer look at the syntax. But you can already see what we have done: put everything in a single variable. But this is not exactly what arrays are. Then what in the world are arrays? Well, simply what we would call, “contiguous storage space”. If we take an analogy, think of a variable as a single box that can hold a single value, but an array is a box with small compartments inside, with the compartments one beside the other in a row. It’s still a box, but can store multiple things.
Variables are like this ( John ), ( 16 ), ( California ) whereas arrays would look like this [ ( John ), ( 16 ), ( California ) ]. The ( and ) are the single compartments.
We have three types of Arrays. They are listed below:
1. Numeric Arrays
2. Associative array
3. Multidimensional array
What is a Numeric Array? Simply, an array with a numerical index. What is an index? It’s a position. Sometimes, the index is also called the “key”.
Before we move on, there is something very important to know about numerical array indices (plural of index): the first position in an array is marked by position #0 (zero). Array indices DO NOT start with one, but zero, so remember this. Therefore, $x would be the 1st position in an array, $x the second, etc. If an array has n elements, the last position would be $x[n-1].
Now let’s have a look at how we write a Numeric array.
We can write write a Numeric array like this
<?php $name = 'John'; $name = 'Richard'; $name = 'Max'; $name = 'Michael'; ?>
In this example, we are assigning the index values manually and this is the long method. What if you had to store a thousand values? Ohh the headache, or finger ache from typing! Do not despair, there is a way to assign values more quickly, and you probably already guessed what it may make use of.
To ouput the values. We can do it like so:
<?php echo $name; // or echo $name for second position value, // $name for third and so on ?>
The best way I found when writing a Numeric Array is like below and same method to output the values:
<?php $persons = array('John','Richard','Max','Michael'); echo $name; ?>
Zero being the Numeric Index for John, 1 for Richard and so on. Each index is between single quote and seperated by a comma. And this is exactly as the big piece of code above.
Now, let’s have a look at Associative Arrays.
As stated earlier, an Associative Array is an array as others, but instead of assigning a number as index, we assign a name to each position, which makes the array more intuitive for us humans to use and understand. Which is easier to understand: $person or $person[‘name’]? The second one is an “assoc” array (short for associative).
<?php $persons = array('John' => '18', 'Richard' => '20', 'Max' => '25', 'Michael' => '30'); ?>
I broke the code in separate lines for easier reading, but you could well put them all in a single line. Depends on what you like. But do not forget those commas! Each index is between single quote, followed by an ‘equal’ sign, then a ‘greater than sign’ which gives us this little arrow ‘=>’ and seperated by a comma.
The names are the keys, and the numbers are the values. So:
Key Values John 18 Richard 20 Max 25 Michael 30
Now how do we output the key and the value? Below is an example:
<?php $persons = array('John' => '18', 'Richard' => '20', 'Max' => '25', 'Michael' => '30');//Remember the caps: John, not john! echo "John is ". $persons['John']. " years old";
What we are doing here is, get the age of John and output it. What does that dot mean anyway? It’s what we call concatenation. Well, what is concatenation then? Just as its dictionary meaning says: stuff things together. What we did above is, take the string “John is “, add the age from the array (value = 18) for John into the string, and added (or concatenated) the last part, ” years old”. Note there is a space before years to make things pretty. The final echoed string is: “John is 18 years old”. If you hadn’t put that space, it’d be “John is 18years old”
Finally, let’s have a look at Multidimensional Arrays. Ohh mean-looking word! Naa it’s actually quite simple to understand: a multi-dimensional array is an array made up of arrays, as if it’s a table with rows and columns, each row having a number of columns. How do we represent multidimensional arrays? We use more square brackets. Something like
$person[‘name’] maybe?<?php $persons = array('john'=>array('Mary','Kate','Alex'), 'cars'=>array('BMW'), 'color'=>array('Red','Blue','Yellow') ); ?>
I know, you might say, What the heck is that. Well, it’s simply three arrays inside of one array, as we said above! You can add another key, and pass in an array of values again. Which will give us four arrays in one array. Well, if you want to go crazy, you can have arrays inside arrays inside arrays inside arrays, which are 3 dimensional arrays like $x… or more arrays in arrays. They are called multidimensional arrays for this reason! But avoid going crazy, for everybody else sanity, maintain simplicity!
Let’s have a look at how we can output a value from our Multidimensional Array.In tabular form: 0 1 2 0 John: Mary Kate Alex 1 cars: BMW Ford Toyota 2 color: Red Blue Yellow
$persons = array('John'=>array('Mary','Kate','Alex'),
"cars"=>array('BMW', 'Ford', 'Toyota'),
echo $persons['John'] . " bought a " . $persons['color'] ." ". $persons['cars'];
If you run the above code, you will get “Mary bought a Blue BMW”!
$persons[‘john’] will output ‘Mary’ since Mary is in the zero index position and John is the Key.
$persons[‘color’] will output ‘Blue’ since Blue is the 1 index and color is the Key
$persons[‘cars’] will output BMW.
As a final tip, use indentations for arrays if you like! It’s a lot easier to understand when there are many arrays inside arrays. Also, if you have a string having an apostrophe in it, don’t use single quotes, but instead, use double quotes, e.g. “John’s Apple” and not ‘John’s Apple’ which is invalid. PHP thinks the string ends at “John” and the rest is error.
So what are the different array kinds used for anyway?
Numeric arrays are usually used to store consecutive data, e.g. the order in which numbers are entered in a system as input. Associative arrays gave similar use to numeric arrays, but usually more useful where the data has a name or category. Eg. person has a name, address, etc… so your array $persons could have “name” and “address” as indices. Multidimensional arrays are used to store tabular data, as you saw above. Arrays will be used in the later lessons to retrieve data from the database, among other things.
We hope by now, you know what arrays are and how to use them in PHP.
This post was contributed by Tipa of Mu-Anime
[seriesposts title=”PHP Lessons” titletag=h3 listtype=ul orderby=date name=”PHP Lessons” ]