PHP arrays

In this part of the PHP programming tutorial, we cover arrays. We initialize arrays and read data from them.

Arrays are collections of data. A variable can hold only one item at a time. Arrays can hold multiple items. Most programming languages have various types of collections, including lists, maps, arrays, queues, stacks, and tuples. PHP has a different approach. It has one type of generic collection, an array. Using different syntax, an array in PHP will behave like a list, an array, or a map.

Technically, a PHP array is a map. It is also called an associative array. A map associates values to keys.

Arrays are used to store data of our applications. There are three distinct things we do with arrays. First, we initialize them with application data. Next, we modify data using assignments or PHP array functions. We have quite a few functions that work with arrays. They enable us to modify, sort, merge, slice, shuffle the data inside the arrays. There are specific database handling functions for populating arrays from database queries. Several other functions return arrays. Finally, we display data to the console, or in web applications to the browser.

Initializing arrays

Since PHP 5.4 it is possible to initialize arrays using the short array syntax by using square brackets.

init1.php
<?php

$names = ["Jane", "Lucy", "Timea", "Beky", "Lenka"];

print_r($names);

?>

We create a $names array, which stores five female names. The print_r() function prints a human readable information about the variable.

$ php init1.php 
Array
(
    [0] => Jane
    [1] => Lucy
    [2] => Timea
    [3] => Beky
    [4] => Lenka
)

From the output we can see the names and their indexes by which we can access them.

Traditionally, arrays have been initialized with the array() function. In its simplest form, the function takes an arbitrary number of comma separated values.

init2.php
<?php

$names = array("Jane", "Lucy", "Timea", "Beky", "Lenka");

print_r($names);

?>

Same array of female names is created with the array() function.

Arrays can be initialized by assigning values to array indexes.

init3.php
<?php

$continents[0] = "America";
$continents[1] = "Africa";
$continents[2] = "Europe";
$continents[3] = "Asia";
$continents[4] = "Antarctica";
$continents[5] = "Australia";

print_r($continents);

?>

We create the $continents array by assigning values to array indexes. "America" has index 0, "Europe" has index 2 etc.

init4.php
<?php

$continents = [ 1 => "America", 2 => "Africa",
    3 => "Europe", 4 => "Asia", 5 => "Antarctica", 
    6 => "Australia" ];

print_r($continents);

?>

In this example, we create the $continents array with the indexes specified. By default, the first index is zero. In our case, we start with 1.

$ php init4.php 
Array
(
    [1] => America
    [2] => Africa
    [3] => Europe
    [4] => Asia
    [5] => Antarctica
    [6] => Australia
)

Now we have an array of continents with indexes that we have chosen.

The indexes do not have to be consecutive numbers.

init5.php
<?php

$languages[10] = "PHP";
$languages[20] = "Python";
$languages[30] = "Ruby";
$languages[40] = "PERL";
$languages[50] = "Java";

print_r($languages);

?>

In the example, we have chosen numbers 10, 20, 30, 40, and 50 to be the indexes for the $languages array.

When we do assignment initialization of a PHP array, we can omit the indexes. PHP automatically creates the indexes for us.

init6.php
<?php

$actors[] = "Philip Seymour Hoffman";
$actors[] = "Tom Cruise";
$actors[] = "Bill Paxton";
$actors[] = "Adrien Brody";
$actors[] = "Danie Craig";

print_r($actors);

?>

An array of actors is created. No specific indexes are set.

$ php init6.php 
Array
(
    [0] => Philip Seymour Hoffman
    [1] => Tom Cruise
    [2] => Bill Paxton
    [3] => Adrien Brody
    [4] => Danie Craig
)

The PHP interpreter has created consecutive indexes starting from zero.

init7.php
<?php

$novels[10] = "Doctor Zhivago"; 
$novels[11] = "War and Peace"; 
$novels[] = "In Cold Blood"; 
$novels[20] = "Crime and Punishment"; 
$novels[] = "Catch XII"; 

print_r($novels);

?>

In this script, we have omitted two indexes. The PHP will add them. It will create index 12 and index 21.

$ php init5.php 
Array
(
    [10] => Doctor Zhivago
    [11] => War and Peace
    [12] => In Cold Blood
    [20] => Crime and Punishment
    [21] => Catch XII
)

PHP has automatically created indexes 12 and 21.

The keys of an array can be strings too.

init8.php
<?php

$countries = [
    "de" => "Germany", "sk" => "Slovakia",
    "us" => "United States", "ru" => "Russia",
    "hu" => "Hungaria", "pl" => "Poland" ];

echo $countries["de"] . "\n";
echo $countries["sk"] . "\n";

?>

We create a $countries array with string indexes.

$ php init8.php 
Germany
Slovakia

This is the output of the init8.php example.

Perusing arrays

Next we will read the contents of the arrays. There are several ways how we can display data from an array.

peruse1.php
<?php

$languages[10] = "PHP";
$languages[20] = "Python";
$languages[30] = "Ruby";
$languages[40] = "PERL";
$languages[50] = "Java";

echo $languages[10], "\n";
echo $languages[20], "\n";
echo $languages[30], "\n";
echo $languages[40], "\n";
echo $languages[50], "\n";

?>

We can access data from an array by their index.

$ php peruse1.php 
PHP
Python
Ruby
PERL
Java

We have printed all five languages to the console.

peruse2.php
<?php

$continents = [ "America", "Africa", "Europe", 
    "Asia", "Australia", "Antarctica" ];

$len = count($continents);

for ($i = 0; $i < $len; $i++) {
    echo $continents[$i], "\n";   
}

?>

In this example, we use the for statement to peruse a $continents array.

$len = count($continents);

First, we count the number of elements in the array with the count() function.

for ($i = 0; $i < $len; $i++) {
    echo $continents[$i], "\n";   
}

The for loop prints elements from the array by indexes 0..$len-1.

peruse3.php
<?php

$continents = [ "America", "Africa", "Europe", "Asia", 
    "Australia", "Antarctica" ];

foreach ($continents as $continent) {
    echo $continent, "\n";    
}

?>

The easiest way to peruse an array is to use the foreach statement. The statement goes through the array one by one and puts a current element to the temporary $continent variable. It accesses data without using their index or key.

walk.php
<?php

$countries = [ "de" => "Germany", "sk" => "Slovakia",
    "us" => "United States", "ru" => "Russia",
    "hu" => "Hungaria", "pl" => "Poland" ];

function show_values($value, $key) { 

    echo "The $key stands for the $value\n";
}

array_walk($countries, 'show_values');

?>

In the last example, we use the array_walk() function to peruse an array. It applies a user function to every member of an array. The user function takes the key and the value of the item as parameters.

$ php walk.php 
The de stands for the Germany
The sk stands for the Slovakia
The us stands for the United States
The ru stands for the Russia
The hu stands for the Hungary
The pl stands for the Poland

We print both the key and the value to the console in the sentence.

In this part of the PHP tutorial, we worked with arrays. We initialized the arrays and read data from them. In the next chapter, we will work with various PHP array functions.