The Basics of Working With PHP Arrays

June 4, 2009 by: Allen Sanford

An array in PHP is simply a variable that is used to store data. Most of the time this data has some sort of common denominator. You will see a lot of code storing things like table row data in arrays. Using arrays also allows you do do some neat things that would be other wise difficult like sorting data and comparing data.

Before you can use an array in PHP you have create a variable and declare it as an array. Now there are actually several ways to accomplish this som let me drop an example in right here.

?Download example.php
22
23
24
25
26
27
28
29
30
    //...
    $array1 = array();
    $array2 = array("Allen", "Sanford");
    $array3 = array("firstname" => "Allen", "id" => 423567123);
    $array4[0]['firstname'] = "Allen"; // This is a multi-dimensional array example
    $array4[0]['lastname'] = "Sanford"; // This is a multi-dimensional array example
    $array4[1]['firstname'] = "John"; // This is a multi-dimensional array example
    $array4[1]['lastname'] = "Doe"; // This is a multi-dimensional array example
    //...

And some of you may be asking can you mix and match those, and the answer is yes you can mix and match those examples. Also it is important to note that unlike some languages PHP will allow you to store different data types in a single array. You can also store other arrays in a single array letting you do all the cool multi-dimensional array stuff. Arrays in PHP can have both numeric indexes or string indexes (which are called associative arrays), however they can not be mixed.

Now that you have defined an array you will need to be able to use the information contained in the array(s). For this again you have several options so I will drop another example to show you how you could display the information contained in your array.

?Download example
32
33
34
35
36
37
38
39
40
41
42
    //...
    // Using the data set form the previous example
    echo $array2[0]; // Allen
    echo $array4[1]['firstname']; // Doe
 
    foreach ($array3 as $key => $value)
        echo $key . " = " . $value . "\n"; // last line will output: id = 423567123
 
     foreach ($array4 as $tempArray)
        echo $tempArray['firstname']; // You should get the picture by now
    //...

This should get you started working with PHP arrays. There are many advanced concepts that I am going to cover in future articles release here on Blogternals. I will be covering Iterators, Hashes, and tree implementations as well as some not so intuitive but useful uses for arrays in PHP.

Filed under: PHP
Tags: , ,

Leave a Reply