Welcome to The PHP Blog!
  Welcome to The PHP Blog on the 29th of July!
RSS 2.0
Read the Feed
The PHP Blog
bare-basics-arrays
Dan
January 9, 2009
Basics

Bare Basics - Arrays

One thing you can’t escape in your PHP journey is arrays, at one point or another they’ll crop up in your simple script, your project or anything in between. Arrays are relatively to simple to use, but can be a bit daunting for people new to programming or just PHP.

Today we’ll look at arrays from a simple array, to a key and value array, finally we’ll have a look at expanding on arrays with a multi-dimensional array.

What is an array?

The concept of arrays are simple. If you create a variable to store a value, it does exactly that, stores a single value. Whether it’s an integer, string or anything in between. An array is basically a variable that can hold multiple values. Arrays have many uses, but that’s a little beyond what we’re looking at in this tutorial, we’re just trying to get to grips with them for now. Let’s look at the basic syntax for an array;

<?php

$my_array[0] = 'Red';
$my_array[1] = 'Green';
$my_array[2] = 'Blue';

?>

Here we’ve created an array that holds three different values, Red, Green and Blue respectively. These values can be referenced by their number, 0-2. An important note is that arrays are typically started from 0, so in our array which holds values 0-2, there are three values. Forgetting to count the 0 as a number in programming is often called a fencepost error (or off-by-one error). The values are accessed in the same way they are set;

<?php

// echo's 'Red and Blue' (without quotes)
echo $my_array[0] . ' and ' . $my_array[2];

?>

Using arrays in this way can have many uses, but let’s say for arguments sake (so we have something to learn) that we want to store the hex values for the colours (or ‘colors’ for those who choose to butcher the english language!), why not? Let’s have a look at two solutions, one is the bad solution using variables that you so often see in newbie projects, one is the better solution using arrays;

<?php

// messy, messy, messy!
$colour_one_name = 'Red';
$colour_one_hex = '#ff0000';
$colour_two_name = 'Green';
$colour_two_hex = '#00ff00';
$colour_three_name = 'Blue';
$colour_three_hex = '#0000ff';

// the better approach
$colours['red'] = '#ff0000';
$colours['green'] = '#00ff00';
$colours['blue'] = '#0000ff'; 

?>

As you can see, the array approach is much tidier and saves a lot of lines of code in comparison to the variable approach. Ok now we’ve learnt the basics of an array, it can hold a number and a value or a key and a value. Well what if we wanted to store something like employee details (how cliche), we’ll need a sort of… array-within-an-array scenario?…

Multi-Dimensional Arrays

Ooooh, doesn’t it sound scary? Have no fear, multi-dimensional arrays, or associative arrays, may have a big name but they’re actually very simple (and even more useful!). So let’s go back to that previous situation of employee records, of course with what we’ve learnt so far we could come up with something that could work…

<?php

$employee_one['name'] = 'Dan Walker';
$employee_one['email'] = 'dan[at]thephpblog[dot]com';
$employee_one['gender'] = 'm';
$employee_one['salary'] = 99999999; // one day....

$employee_two['name'] = 'Joe Bloggs';
$employee_two['email'] = 'joe[at]bloggs[dot]com;
$employee_two['gender'] = 'm';
$employee_two['salary'] = 20000; // one day....

?>

The above works, we’ve created two arrays, one for each employee, and filled it with data using the key and value method we learned about earlier. That’s great, but what if we wanted to create a loop that displayed all our employee names or something? Well then we’d be pretty screwed because they have different names and we’d have to recode everything every time we added a new employee! Not good! But what if we could put a key and value array inside a standard incremental array. Now you’re thinking!

<?php

$employees[0]['name'] = 'Dan Walker';
$employees[0]['email'] = 'dan[at]thephpblog[dot]com';
$employees[0]['gender'] = 'm';
$employees[0]['salary'] = 99999999;

$employees[1]['name'] = 'Joe Bloggs';
$employees[1]['email'] = 'joe[at]bloggs[dot]com';
$employees[1]['gender'] = 'm';
$employees[1]['salary'] = 20000;

?>

Note: Notice that the salary values do not have quotes round them, that’s because they’re integers - arrays can hold different types of data just as a variable can.
Now that my friend is looking a lot cleaner. The logic is simple, $employees[0] now contains another array, as does $employees[1]. Because these arrays are nested within another array, this is where we get the name multi-dimensional array from (as if you hadn’t already guessed that).

Because we’ve done it this way we can now cycle through loops to do stuff, let’s say we want to list all our employee names, this is how we’d do it.

<?php

$employees[0]['name'] = 'Dan Walker';
$employees[0]['email'] = 'dan[at]thephpblog[dot]com';
$employees[0]['gender'] = 'm';
$employees[0]['salary'] = 99999999;

$employees[1]['name'] = 'Joe Bloggs';
$employees[1]['email'] = 'joe[at]bloggs[dot]com';
$employees[1]['gender'] = 'm';
$employees[1]['salary'] = 20000;

for ($i=0; $i<count($employees); $i++)
{
	echo $employees[$i]['name'] . '<br />';
}

?>

Would list the two employee names on different lines. You see if we use count($employees) then it counts how many values are in the top layer of our array, the first brackets. There are 2 values in this array and so the loop loops twice. It’s important to remember we start the loop from 0 because our array starts from 0.

Conclusion

Of course this has just been the basics of arrays, if you’re interested in how we could use an array like our employees one, why not take a look at my PHP MySQL class which stores its results in a multi-dimensional array.

Thanks for reading, questions and comments welcome =]


Sponsored By

Comments


  1. Angelo R
    16:40 On December 28th, 2008

    This is a great tutorial, you should definitely cover some of the advanced array functions present in PHP though. A lot of people use arrays, and then create their own convoluted loops (I know I used to) for doing things, that could be easily done with just built in function.

  2. Tutorials Room
    19:18 On December 28th, 2008

    Clear and simple! it was added to the homepage of http://www.tutorialsroom.com
    Waiting for more of your good tutorials :D

  3. The PHP Blog » More Advanced Arrays - PHP Tutorials - MySQL Tutorials
    10:49 On January 14th, 2009

    [...] so hopefully you read this tutorial first so that you have a basic understanding of the different types of array and what we can store in [...]

  4. » More Advanced Arrays
    03:42 On February 9th, 2009

    [...] so hopefully you read this tutorial first so that you have a basic understanding of the different types of array and what we can store in [...]

  5. PHP Basic Array « Maverick’s Blog
    09:43 On February 27th, 2009

    [...] course this has just been the basics of arrays….. Source: PHPBlog [...]

  6. Anks
    12:31 On March 2nd, 2009

    Hey I posted ur tutorial in my blog and referred ur site there so I dont think so u r facing any problem wid that …. :)

  7. TD
    18:56 On June 23rd, 2009

    I tried to locate your PHP MySQL Class but I can’t find it. Do you still have it?

Post Your Comments







The PHP Blog loves gravatars, get yours today!