Broad Network


The PHP Indexed Array

Array in PHP – Part 1

Foreword: In this part of the series I talk about the PHP indexed array.

By: Chrysanthus Date Published: 26 Jan 2014

Introduction

This is part 1 of my series, Array in PHP. In this part of the series I talk about the PHP indexed array. The PHP indexed array is the array for which you access a value using an index (0 or 1 or 2 or 3, etc.). This is a tutorial.

Note: the output of all the code samples in this series are sent to the browser.

Note: in this article, if you cannot see any text or piece of code or if you think something (e.g. an image) is missing or link does not operate, or just want to comment, contact me at forchatrans@yahoo.com .

Pre-Knowledge
There are certain topics you need to have covered before you can understand this series. Click the link titled, “PHP Course” below to know what you should have studied before reaching here. This series is part of my volume, PHP Course.

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 computer languages 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 also 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 above 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 corresponding values are, 13, “bar”, 23, “woman” and “man tomorrow”. A number as a key is not in quotes. A number as a value is not in quotes.

An array, is code that can house any of the above tables and similar tables. Note that element (value) position counting begins from zero and not 1.

Note: Each key/value pair in an array, together with its surrounding code is called an element.

The Indexed Array

An indexed array is one where the keys are all integers. The index counting begins from zero. For the rest of this tutorial, I talk only about the indexed array. The first table above is very suitable for a PHP indexed array. The other two tables should not be used for an indexed array (see later).

Creating an Array
There are two main ways of creating an array in PHP: You can create an array by initialization or you can create an array by variable declaration. Array by Initialization is a term I have borrowed from C++.

Creating Indexed Array by Initialization
The following two statements show two initialization ways of creating an array for the first table above; only the first five elements have been used in the statements.

   $myArr = array(0 => "John", 1 => "Mary", 2 => "Peter", 3 => "Augustine", 4 => "Angela");

   $myArr = array("John", "Mary", "Peter", "Augustine", "Angela");

You begin an array with the variable of the array, e.g. $myArr. The variable is like any other variable. Next you have the assignment operator and then the array construct, which is, array(). In the parentheses of the array function, array(), you have the key/value pairs or the values. The first statement above has key/value pairs. The pairs are separated by commas. Within a pair the key is separated from the value by the => operator (= followed by >). The second statement has only the values. The values are separated by commas.

In the first statement the integers (numbers) are the indices. These indices are the keys. The first statement and the second statement do exactly the same thing. This means from the second statement, that typing the indices when creating an array is optional. If you do not type the indices as in the second statement, the PHP interpreter produces the indices internally, for you.

It is possible for all the values in the array to be integers. So, when creating an array and while omitting the indices, be careful not to confuse between the indices and the values. Consider the following statement:

   $arr = array(10, 20, 30, 40, 50);

Here, the numbers, 10, 20, 30, etc are values and not indices.

Creating Indexed Array by Variable Declaration
You can create an array by just declaring the variable as follows:

   $myArr;

Now, it is you the programmer who knows that at this point in the program, the variable will hold an array (good to comment about there in code). At the point, values have not been added yet. Below in the code, you can assign the array values as follows:

   $myArr;

   $myArr[0] = "John";
   $myArr[1] = "Mary";
   $myArr[2] = "Peter";
   $myArr[3] = "Augustine";
   $myArr[4] = "Angela";

Each array variable below the declaration has the pair of square brackets in which there is an index. Note: PHP allows you to create an array without even declaring the variable. In this case there is indirect declaration. So you can create an array for the first table above without formally declaring the variable as follows (I have used just 5 elements):

   $myArr[0] = "John";
   $myArr[1] = "Mary";
   $myArr[2] = "Peter";
   $myArr[3] = "Augustine";
   $myArr[4] = "Angela";

You are not obliged to type the indices (0, 1,  2, etc.). If you do not type the indices, PHP will do that for you internally, without you knowing. So, this array can equally be created as follows:

   $myArr[] = "John";
   $myArr[] = "Mary";
   $myArr[] = "Peter";
   $myArr[] = "Augustine";
   $myArr[] = "Angela";

If you are using indices, then the indices can be typed in any order. So, the array can equally be created as follows:

   $myArr[3] = "Augustine";
   $myArr[1] = "Mary";
   $myArr[4] = "Angela";
   $myArr[0] = "John";
   $myArr[2] = "Peter";

Reading the Value of an Element
The syntax to read the value of an element is:

    $arrayName[index]

Read and try the following code:

<?php

    $myArr;

    $myArr[3] = "Augustine";
    $myArr[1] = "Mary";
    $myArr[4] = "Angela";
    $myArr[0] = "John";
    $myArr[2] = "Peter";

    $var = $myArr[4];

    echo $var;

?>

The output from the echo statement is:

    Angela

Changing the Value of an Element
To change the value of an element, just assign a new value with the syntax,

    $arrayName[index] = newValue

Read and try the following code:

<?php

    $myArr;

    $myArr[0] = "John";
    $myArr[1] = "Mary";
    $myArr[2] = "Peter";
    $myArr[3] = "Augustine";
    $myArr[4] = "Angela";

    $myArr[2] = "James";

    echo $myArr[2];

?>

The output from the echo statement is:

    James

Skipping Indices
You do not have to create the array with consecutive indices. In

   $myArr = array(1 => "Mary", 3 => "Augustine");

indices 0 and 2 have been skipped; the statement will operate very well. In

   $myArr;

   $myArr[0] = "John";
   $myArr[2] = "Peter";
   $myArr[4] = "Angela";

indices 1 and 2 have been skipped ; the code segment will operate very well.

Adding Un-indexed Element after Skipping
If after skipping (or even without skipping) you add an un-indexed element, PHP gives the next index to the element. This next index is the current highest index plus 1. In the above code, the index given would be 5.

The print_r() Function
This predefined function prints an array in a format that shows the keys and values. The syntax is:

    print_r($arrayName)

However, if you are using a web page for your output as in this series, the array will not be properly displayed. This is because the formatting output of the function uses newline (\n) characters instead of <br>. So, to see the function output properly, you would have to open the source text page of the web page. The function output is displayed properly at the source text page. To open the source text page, right-click anywhere in the web page and you will see a popup menu. In the pop up menu, click the command with the title “View Page Source” or “View Source” or something similar.

Read and try the following code:

<?php

    $myArr = array(3 => "Augustine", 1 => "Mary");
    $myArr[] = "Angela";
    print_r($myArr);

?>

From my computer, the output of the text source page is:

Array
(
    [3] => Augustine
    [1] => Mary
    [4] => Angela
)

Note that the index added by PHP in the code, is the current highest index, which is 3, plus 1, giving 4.

Adding a New Indexed Element
To add a new indexed element is simple: use the syntax:

    $arrayName[newIndex] = value

where newIndex is an integer, which is not already an index in the list. It does not necessarily have to be the current highest index plus 1; it is any index that is not already present, even much higher than the current highest index. The following code, which you should read and try, adds two new indices (and corresponding values):

<?php

    $arr = array(1 => 11, 3 => 33, 4 => 44);
    $arr[2] = 22;
    $arr[6] = 66;

    print_r($arr);
    
?>

The output is:

Array
(
    [1] => 11
    [3] => 33
    [4] => 44
    [2] => 22
    [6] => 66
)

If you use an index that already exists, you replace the corresponding value.

Simple Removal of Element
A simple way to remove the key of an element is to use the predefined unset() function. This simply hides the element without really removing the index. If you use the unset() function to remove highest indexed element for example, then you go on to add a new un-indexed element, the new index will not replace the supposed removed index. Read and try the following code:

<?php

    $myArr;

    $myArr[0] = "John";
    $myArr[1] = "Mary";
    $myArr[2] = "Peter";

    unset($myArr[2]);

    $myArr[] = "Augustine";

    print_r($myArr);
    
?>

The output is:

Array
(
    [0] => John
    [1] => Mary
    [3] => Augustine
)

Note at the output that index 2 has not been replaced.

You can still use the unset() function to remove (hide) all the elements of the array. In this case the argument to the unset() function is the array variable without the square brackets and index. Read and try the following code, but note that the keys (indices) are not really removed.

<?php

    $myArr;

    $myArr[0] = "John";
    $myArr[1] = "Mary";
    $myArr[2] = "Peter";
    $myArr[3] = "Augustine";
    $myArr[4] = "Angela";

    unset($myArr);

    print_r($myArr);
    
?>

The output display shows nothing.

The array_values() Function
The unset() function does not really remove the elements and does not re-index the elements. Re-indexing means giving the remaining element indices consecutive integers from 0 to the last index, which is length of seen elements minus 1. The array_values() function does that. It takes as argument, the array variable on which the unset() function has acted upon and returns a new re-indexed array having no hidden(unseen) element. So the array on which unset() acted upon, remains unchanged, but you have a new returned array from the array_values() function. Read and try the following code:

<?php

    $myArr;

    $myArr[10] = "Simon";
    $myArr[6] = "Susan";
    $myArr[8] = "Grace";
    $myArr[9] = "Pearl";
    $myArr[7] = "Martin";

    unset($myArr[10]);
    unset($myArr[8]);

    $newArr = array_values($myArr);

    print_r($newArr);
    
?>

The output is:

Array
(
    [0] => Susan
    [1] => Pearl
    [2] => Martin
)

The re-indexing has followed the placement order of the seen elements and not the index order of the seen elements.

String and Numbers mixed as Values
For an indexed PHP array the indices are integers, while the values in the same array can be both strings and numbers. Read and try the following code:

<?php

    $arr;

    $arr[0] = "zero";
    $arr[1] = 1;
    $arr[2] = "two";
    $arr[3] = 3.5;
    $arr[4] = "eeee";
    $arr[5] = 5;

    print_r($arr);
    
?>

The output is:

Array
(
    [0] => zero
    [1] => 1
    [2] => two
    [3] => 3.5
    [4] => eeee
    [5] => 5
)

That is it for this part of the series. It has been a long ride. We take a break here and continue in the next part of the series.

Chrys

Related Links

Basics of PHP
PHP Directory Function Basics
Understanding PHP Reference
PHP Function Arguments
Understanding Variable Scope in PHP
Object Oriented Programming in PHP
PHP Data Types Simplified
Exception Handling in PHP
PHP Regular Expressions
Sending Email with PHP
PHP Strings
Date and Time in PHP
PHP String Functions for Website Design
Advanced Course
PHP Variable Scope
Advanced Features of PHP Function
Array in PHP
PHP Two Dimensional Arrays
Understanding Object Oriented Programming in PHP
Advanced PHP Regular Expressions
Some features of PHP Entities
PHP Namespace
PHP Web Application

More 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