Broad Network


PHP Array

Basics of PHP – Part 10

Forward: In PHP an array is an ordered map where values are associated to keys. I explain all that in this article and how to use a PHP array.

By: Chrysanthus Date Published: 28 Jul 2012

Introduction

This is part 10 of my series, Basics of PHP. In PHP an array is an ordered map where values are associated to keys. I explain all that in this article and how to use a PHP array. PHP array is different from arrays in other programs.

Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.

Some Array Content Examples
Imagine that you are a proprietor of a small company, and you have 10 employees. In your PHP program, you can have their first names in an array. Each listed item here is a first name. Let the list be:

1 John
2 Mary
3 Peter
4 Augustine
5 Angela
6 Susan
7 Martin
8 Grace
9 Pearl
10 Simon

In other programs the integers of the list are called indices and the first names are called values. In PHP the integers are called keys and the first names are still called values.

Now, consider five first names of students in a middle school. The following table gives the first names on one hand and the age and grade on the other hand.

Anthony   “10, 7”
Catherine  “10, 8”
Ursula       “11, 8”
Gladys       “13, 9”
Sandra       “10, 7”

Here the keys are the first names. The values are strings. In each string you have the age and grade, which are separated by a comma. A PHP array can take the first table or this table. A PHP array consists of key/value pairs. Values are usually literals. Now, the keys do not only have to be all integers or all texts. They can be mixed; integers and text, like in the following hypothetical table:

foo      13
9          “bar”
man       23
5           “woman”
boy       “man tomorrow”

Here the keys are foo, 9, man, 5 and boy. The values are, 13, “bar”, 23, “woman” and “man tomorrow”.

Note; when putting a table in an array, if the key is text, it has to be in single or double quotes. Also note that element (value) position number counting begins from zero and not 1.

Note: Array values are called elements.

Creating an Array
You can create an array with the key/value pairs at the same time or you can create an array empty, and then put in the key/value pairs afterward. To create an array for the last table above, you would do,

        $myArr = array("foo" => 13, 9 => "bar", "man" => 23, 5 => "woman", "boy" => "man tomorrow");

$myArr is a name you the programmer gives for the array. It is followed by the assignment operator; then the reserved word, array; then parentheses. In the parentheses, you have the key/value pairs. Each key that is text must be in single or double quotes. The key/value pairs are separated by commas. Note the use of => in each key/value pair. Each key that is an integer does not have to be in quotes. Each value that is a number (integer or float) does not have to be in quotes.

You can create an empty array and then put the key value pairs later. To create an empty array you do this,

        $myArr = array();

$myArr is just a name you give. To put in the key/value pairs of the last table, you do

        $myArr["foo"] = 13;
        $myArr[9] = "bar";
        $myArr["man"] = 23;
        $myArr[5] = "woman";
        $myArr["boy"] = "man tomorrow";

For each key/value pair, you begin with the variable of the array. This is immediately followed by square brackets. Within the square brackets, you have the key. If the key is text, it is in quotes (single or double). If the key is an integer, it is not in quotes. This is followed by the assignment operator and then the value. If the value is a string (single or double), it is in quotes; if it is a number, it is not in quotes. Note: a key can be an integer, but it cannot be a float.

Accessing an Array Value
The syntax to access an array value is,

    $arrayName[key]

Text key should be in quotes. So if you want to access the third value for the above array, you would do,

    $myArr["man"]

The value returned can be assigned to a variable, something like:

    $myVar = $myArr["man"];

Read and try the following code, where the third value is displayed twice:

    <?php

        $myArr = array();

        $myArr["foo"] = 13;
        $myArr[9] = "bar";
        $myArr["man"] = 23;
        $myArr[5] = "woman";
        $myArr["boy"] = "man tomorrow";

        echo $myArr["man"], "<br />";

        $myVar = $myArr["man"];
        echo $myVar;

    ?>

Changing the Value for a Key
You change a value for a key by just assigning a new value for the key. To change the value of the fourth key of the above table, you would do something like:

        $myArr[5] = "girl";

Appending a key/value Pair with the Square Bracket Syntax
Appends means add at the bottom. You append a key/value pair by just assigning the new value for the new key with the square bracket syntax, something like:

        $myArr["newKey"] = "new value";

You may decide not to have a key. In that case you do something like:

        $myArr[] = "new value";

In this case the interpreter gives you an integer as key. The integer given is the highest integer already present as key in the array, plus 1. For the above table of mixed key types, it would be 10, since the highest integer key present is 9. What about the case where the array does not have any integer key? In such a case the integer given is zero. After that the array would have one integer as key and the rest would be texts.

Array Functions
There are many functions you can use to affect an array. I will give you just a few. Note: when calling a function, you need to use parentheses.

The count Function
This function gives you the number of elements (values) in the array. The simplified syntax for this is:

    int count($arrayName)

The int means the function returns an integer, which is the number of elements in the array. You can assign the return value to a variable or you can use the count function in some expression. Read and try the following:

    <?php

        $myArr = array();

        $myArr["foo"] = 13;
        $myArr[9] = "bar";
        $myArr["man"] = 23;
        $myArr[5] = "woman";
        $myArr["boy"] = "man tomorrow";

        echo count($myArr);

    ?>

The value returned is 5.

The array_shift Function
This function removes the first element from an array and returns that element. Read and try the following code:

    <?php

        $myArr = array();

        $myArr["foo"] = 13;
        $myArr[9] = "bar";
        $myArr["man"] = 23;
        $myArr[5] = "woman";
        $myArr["boy"] = "man tomorrow";

        echo array_shift($myArr); echo "<br />";
        echo count($myArr);

    ?>

A simplified syntax for the array_shift function is:

    mixed array_shift($arrayName)

Here, mixed, means the returned value can be of any type. It can be a float or a string for example. If it is a string, it is returned without the quotes.

The array_pop Function
The array_pop function removes the last element from an array and returns that element. Read and try the following:

    <?php

        $myArr = array();

        $myArr["foo"] = 13;
        $myArr[9] = "bar";
        $myArr["man"] = 23;
        $myArr[5] = "woman";
        $myArr["boy"] = "man tomorrow";

        echo array_pop($myArr); echo "<br />";
        echo count($myArr);

    ?>

A simplified syntax for the function is:

    mixed array_pop ($arrayName)

The sort Function
This function sorts the values of an array, arranging them in alphabetical order and/or from lowest to highest. Read and try the following code:

    <?php

        $myArr = array();

        $myArr["foo"] = 13;
        $myArr[9] = "bar";
        $myArr["man"] = 23;
        $myArr[5] = "woman";
        $myArr["boy"] = "man tomorrow";

        sort($myArr);
        print_r($myArr);

    ?>

The print_r function is similar to the echo construct. However, print_r function can send out the individual elements of an array when it has the array variable as argument. The echo construct cannot do this when it has the array variable as argument. In your result for the above code, do not worry much about the indices in square brackets. For now just know that the values of the array have been sorted.

A simplified syntax for the sort function is:

    bool sort($arrayName)

Here, bool means that the return value is either true or false. If the sorting process was successful, true is returned. If it was not successful, false is returned.

The array_push Function
The array_push function appends one or more values to the end of the array. You can add only values; you cannot add the corresponding keys. In this case the interpreter gives you integers as keys. Read and try the following:

    <?php

        $myArr = array();

        $myArr["foo"] = 13;
        $myArr[9] = "bar";
        $myArr["man"] = 23;
        $myArr[5] = "woman";
        $myArr["boy"] = "man tomorrow";

        array_push($myArr, "last but one", "last");
        print_r($myArr);

    ?>

The array has not been sorted, so in the result, the keys are given by the print_r function. Note that 10 and 11, which are the next integers after 9 (the highest available index) have been given as keys for the added values, in the result.

A simple syntax for the array_push function is:

    int array_push($arrayName, value, value, value);

The first item in the parentheses is the array variable, the rest of the items are the values, usually in their literal forms. You can have one or more values, not strictly three as indicated above. All the items in the parentheses are separated by commas.

The returned value of the function is an integer, which is the new total number of elements (count) in the array. In the above case it is 7.

The unset Function
The unset function destroys one or more key/value pairs in an array. Read and try the following code:

    <?php

        $myArr = array();

        $myArr["foo"] = 13;
        $myArr[9] = "bar";
        $myArr["man"] = 23;
        $myArr[5] = "woman";
        $myArr["boy"] = "man tomorrow";

        unset($myArr[9], $myArr["man"]);
        print_r($myArr);

    ?>

A simple syntax for the unset function is:

    void unset ($arrayName[key], $arrayName[key])

Here, void means that the function does not return any value.

There are many other PHP array functions. These array functions are built-in functions in the interpreter; you do not have to write them. You can consult some other document for the other array functions.

We have done a lot. Let us stop here and continue in the next part of the series.

Chrys

Related Links

Major in Website Design
Web Development Course
HTML Course
CSS Course
ECMAScript Course
PHP Course
NEXT

Comments

Become the Writer's Fan
Send the Writer a Message