HTML and PHP Resources

Short easy to follow tutorials & more…

207: Introduction to arrays in PHP

| 0 comments

Introduction

Arrays are a special data type in PHP that is used to hold a list of data. The ability to hold a list of data is valuable as it allows us to hold and pass sets of related data to different point in our application with ease.

Array Syntax

The simplest way to use arrays is it declare one using the array() function when declaring a variable.  There are a couple different ways to add data to an array, we can assign a value to the array with an empty index or by passing the values as parameters to the array() function.

When the array() function is used without any parameters an empty array is created.

PHP
1
$ourList = array();

Passing values as parameters creates a non empty array. Passing a value to the array with an empty index also pushes a value to the end of the array.

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
/* Fill an array by passing values as parameters */
$ourList = array('Hello', 'World'); // pass values as parameters
var_dump($ourList); // Visual Representation of the array.
/* Filling an array by passing an empty index */
$ourList2 = array(); // empty array
$ourList2[] = 'Hello'; // pushes a value into the array
$ourList2[] = 'World'; // pushes a value into the array
var_dump($ourList2); // Visual Representation of the array.

Note: In the case that the array has not been explicitly created, simply using array syntax and assigning it a value will create an array with the key(if any) and values provided.

Array Indices

Arrays hold data as list and  list held by the array needs to be access in order to be useful. If you use a function like var_dump() or print_r() you can see a visual representation of the array like below:

array(2) {
[0]=>
string(5) “Hello”
[1]=>
string(5) “World”
}

Our array consists of two string values with a length of five characters. The important thing to notice is the value in the square brackets, this is the index that is used to refer to that value.

To access a given item in an array we simply use the name of the variable that holds the array and then use the index of the item in square brackets.

PHP
1
2
3
4
5
6
7
8
9
10
11
12
<?php
# Fill an array by passing values as parameters
$names = array('Leon', 'Ivan', 'John', 'Mohamed', 'Jose');
echo $names[0], "<br>\n"; // Displays: Leon
echo $names[1], "<br>\n"; // Displays: Ivan
echo $names[2], "<br>\n"; // Displays: John
echo $names[3], "<br>\n"; // Displays: Mohamed
echo $names[4], "<br>\n"; // Displays: Jose
# Visual representation of array.
var_dump($names);

By default array indices begin at zero and count to one minus the number of elements. So the array above has five elements and the indices range from zero to four.

Note: Indices can also be referred to as keys.

Specifying Indices(keys)

PHP automatically specifies the indices for arrays when none is specified. We can specify a different key starting point or do away with numerical numbering and use a string key names for our arrays indices.

To start numbering at a different value, we simply use the  “=>” operator when we specify our values. It should be noted that the parser will number any indices after that point in sequential order until a different index value is specified.

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php
$br = "<br>\n"; // Used for formatting
/************************** EXAMPLE 1 ************************************/
// Specify the count to start at 1 rather than 0
$ourList = array(1 => 'Mercury', 'Venus');
echo $ourList[1], $br; // Displays: Mercury
echo $ourList[2], $br; // Displays: Venus
/************************** EXAMPLE 2 ************************************/
// Specify the a different index for certain values
$ourList2 = array(1 => 'Mercury', 'Venus', 4 => 'Mars'); // 3 not defined!
echo $ourList2[1], $br; // Displays: Mercury
echo $ourList2[2], $br; // Displays: Venus
echo $ourList2[3], $br; // Displays: Mars
/************************** EXAMPLE 3 ************************************/
// Specify a string key
$ourList3 = array('home' => 'Earth', // key: home value: Earth
'largest' => 'Jupiter', // key: largest value: Jupiter
'center' => 'Sun', // key: center value: Sun
'Astroid Belt'); // key: 0 value: Astroid Belt
echo $ourList3['home'], $br; // Displays: Earth
echo $ourList3['largest'], $br; // Displays: Jupiter
echo $ourList3['center'], $br; // Displays: Sun
echo $ourList3[0], $br; // Displays: Astroid Belt

Note: PHP does not take white space into account when parsing code, for readability the example shows how we can set different keys and values on their own line. Arrays that contains string key names are refereed to as associative arrays

Arrays Inside Arrays

Arrays are nothing more than a list that holds other data types. Arrays can also be multi-dimensional, meaning that they can hold other arrays and those arrays can hold other arrays so on so forth. We can define arrays like the example below, or you can nest array() functions in one another.

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
$family = array();
// key 'adults' contains an array with keys and values
$family['adults'] = array(
'mother' => 'Lea',
'father' => 'Lucas'
);
$family['children'] = array(
'son' => 'Leo',
'daughter' => 'Lisa'
);
echo $family['adults']['father'], "<br>\n"; // Displays: Lea
echo $family['adults']['mother'], "<br>\n"; // Displays: Lucas
echo $family['children']['son'], "<br>\n"; // Displays: Leo
echo $family['children']['daughter'], "<br>\n"; // Displays: Lisa
print_r($family); // Visual Representation of the array

Note: To access the data inside the inner array you specify a key of the array holding the inner array, then the key of the enclosed array.

PHP
1
$variableName['outer array key']['inner array key'];

Note: This pattern continues if more arrays are enclosed.

Array Related Error

While using arrays we may occasionally come across the following error.

PHP
1
Notice: Undefined offset: key in file.php on line 20

Depending on the PHP setting on the server, this may or may not display. In this example this is a PHP notice, which means the rest of our script will finish parsing and continue to be executed, in contrast if this was a fatal error our PHP script would stop executing all together.

All this notice means is we have not defined this particular key for our array. To fix this we need to specify the key the parser is trying to find at(or around) the line it specifies or remove this reference all together, depending on what our script is supposed to be doing.

Summary

Arrays are a special data type in PHP that can hold a list of data including other arrays.  Arrays have sequential numerical keys (indices), but you have the ability to specify string key names or an alternate starting number. Arrays are commonly used to group related data in order to make it simple to pass the data to different parts of an application.

Comments, Questions or Concerns

If you have any comments, questions or concerns feel free to voice them on this site or contact us directly at php@htmlandphp.com

Leave a Reply

Required fields are marked *.

*