Overview of This Lesson

Refresh this page because I am probably still making changes to it.

Arrays in PHP are very similar in concept to arrays in other languages, but probably most similar to arrays in JavaScript. This lesson will go over the basic syntax of creating, accessing, and iterating through arrays, and also some useful array operators and functions.

Resources

Pre-Requisites

Before doing this lesson, you should make sure you're familiar with PHP, PHP Variables and Types and PHP Operators and Structures.

Basic Syntax of Arrays

Arrays in PHP are very similar to arrays in other languages. Each element contains one value and each element is identified by its index or subscript. However, in PHP, arrays are Maps: they are a series of key-value pairs, where the key is the array index and the value is the element value. This means that you can use any unique integer or string as your key/index. The actual element value can be anything.

Creating Arrays

There are a few different ways to create an array in PHP:

This first example creates an array of values using the array() construct:

$languages = array("Java", "PHP", "Perl", "C#", "Visual Basic");

You can do this without the array() construct:

$languages = ["Java", "PHP", "Perl", "C#", "Visual Basic"];

When you use var_dump() with an array, it will give you all the array's contents:

<?php
  $languages1 = array("Java", "PHP", "Perl", "C#", "Visual Basic");
  $languages2 = ["Java", "PHP", "Perl", "C#", "Visual Basic"];
  echo "<pre>";
  var_dump($languages1);
  echo "</pre><pre>";
  var_dump($languages2);
  echo "</pre>";
?>

Because PHP arrays are actually maps, you can also specify the key for each value in the array using the following syntax:

// using array()
$rooms = array(
  "b306" => "White Pine Room",
  "e201" => "Maple Room",
  "h144" => "Willow Room"
);
echo "<pre>";
var_dump($rooms);
echo "</pre>";
// or you can do it with square brackets:
$sideDishes = [
  "naan" => 2.95,
  "dhal" => 3.95,
  "kitchari" => 4.95,
  "sag aloo" => 3.95,
  "mango chutney" => 1.95,
  "raita" => 1.95
];
echo "<pre>";
var_dump($sideDishes);
echo "</pre>";

Both examples create the same array, but using different syntax.

You can also hard-code an array one element at a time:

$languages[0] = "Java";
$languages[1] = "PHP";
$languages[2] = "Perl";
$languages[3] = "C#";
$languages[4] = "Visual Basic";

echo "<pre>";
var_dump($languages);
echo "</pre>";

In fact, if you know your indexes will be sequentially numeric, the following will also be correct:

$languages[] = "Java";
$languages[] = "PHP";
$languages[] = "Perl";
$languages[] = "C#";
$languages[] = "Visual Basic";

However, likely this isn't something you would do unless you were using a loop or a function:

$numbers = [7, 11, 41, 97, 37, 19];
  $roots = [];
  for ($i = 0; $i < count($numbers); $i++) {
      $roots[] = sqrt($numbers[$i]);
  }
  echo "<pre>";
  var_dump($roots);
  echo "</pre>";

The above example creates an array with some numbers, and then uses that array to create an array with the square roots of those numbers called $roots. The key of $roots is the number and the value is the square root of the number. When you look inside the $roots array using var_dump(), you see output similar to this:

array(6) {
  [0]=> 
    float(2.6457513110646)
  [1]=> 
    float(3.3166247903554)
  [2]=> 
   float(6.4031242374328)
  [3]=>
   float(9.8488578017961)
  [4]=>
   float(6.0827625302982)
  [5]=>
   float(4.3588989435407)
}

Notice that we use the count() function to get the number of elements in the array, or the size or length of the array. In other languages, you're probably used to doing this with some kind of array or collection property or method, but in PHP you use count($arrayName), where $arrayName is the variable that contains the array.

Accessing Elements

You can access individual array elements by specifying the index in square brackets:

$languages = ["Java", "PHP", "Perl", "C#", "Visual Basic"];
  echo "<p>This course is about $languages[1].</p>";
    
$sideDishes = [
    "naan" => 2.95,
    "dhal" => 3.95,
    "kitchari" => 4.95,
    "sag aloo" => 3.95,
    "mango chutney" => 1.95,
    "raita" => 1.95
];
echo "<p>Today's special is $".number_format($sideDishes['kitchari'], 2)."</p>";

The code above outputs:

This course is about PHP.
Today's special is $4.95

If you try to access elements that don't exist, the expression will return a null value:

$languages = ["Java", "PHP", "Perl", "C#", "Visual Basic"];
echo "<p>This course is about $languages[10].</p>";
      
$sideDishes = [
    "naan" => 2.95,
    "dhal" => 3.95,
    "kitchari" => 4.95,
    "sag aloo" => 3.95,
    "mango chutney" => 1.95,
    "raita" => 1.95
];
echo "<p>Today's special is $".number_format($sideDishes['foo'], 2)."</p>";
  

This code outputs:

This course is about .
Today's special is $0.00

Note that if you have error/warnings turned on, you will see warnings about using undefined offset/index.

Another interesting thing to note about arrays is that if you access an element on an array that you haven't defined yet, PHP will create the array for you and then add the element:

<?php
    $foo["bar"] = 77;
    var_dump($foo);
?>

This example's output shows that the array has on element with a key of "bar" that contains the value 77:

array(1) { 
    ["bar"]=> int(77) 
}

The Foreach Loop

The foreach loop provides an easy way to loop through an array (and you can also use it to traverse the properties of an object, as you'll see in a later lesson). There are two syntaxes you can use for the foreach loop. The first version is:

foreach(array_expr as $value) {
   statement(s) to repeat for each $value in the array expression
}

array_expr is the array, or an expression that yields an array, and $value is the parameter that contains each array element in each iteration.

For example, to print all the elements of the $languages array:

<?php
  echo "<p>Languages I know:</p>\n<ul>";
  $languages = ["Java", "PHP", "Perl", "C#", "Visual Basic"];
  foreach ($languages as $aLang) {
      echo "<li>$aLang</li>";
  }
  echo "</ul>";
?>

This example displays the contents of the $languages array inside an unordered list.

an unordered list containing java, php, perl, c#, and visual basic
The output from the code sample: the contents of the array in an unordered list

That first version of the foreach syntax is useful if you're using standard, sequential numeric indexes. However, if you're using other unique values as keys, such as strings or non-sequential numbers, you will find the second version of the foreach is more useful:

If you have keys that aren't sequential numbers starting from 0,

foreach(array_expr as $key => $value) {
    statement(s) to repeat for each $key/$value pair in the array expression
}

As with the first version, array_expr is any array or any expression that yields an array. The $key parameter contains the name of an element's key and the $value paramter contains the value associated with that specific $key.

<?php
  $sideDishes = [
    "naan" => 2.95,
    "dhal" => 3.95,
    "kitchari" => 4.95,
    "sag aloo" => 3.95,
    "mango chutney" => 1.95,
    "raita" => 1.95
  ];
  echo "<p>List of side dishes:</p>\n<ul>";
  foreach($sideDishes as $side => $price) {
      echo "<li>$".number_format($price, 2)." $side</li>";
  }
  echo "</ul>";
?>
an unordered list containing the side dishes and their prices
The output from the code sample: the contents of the array in an unordered list

Both versions of the foreach loop only allow for read-access to the array. However, if you'd like to be able to modify the $value and thus modify the array element inside the foreach loop, prefix $value with the & ampersand character:

<?
  $numbers = [7, 11, 41, 97, 37, 19];
  foreach ($numbers as &$num) {
      $num = sqrt($num);
  }
  unset($num);
  var_dump($numbers);
?>

We add the unset($num) after the loop because of how references work: after the loop, $num still references the last element value in the array. If you change $num after the loop, you'll actually be changing the last element in the array unintentionally. The unset() function destroys the $num variable so that it no longer references the last array element.

The above code produces the output:

array(6) { 
    [0]=> float(2.6457513110646) 
    [1]=> float(3.3166247903554) 
    [2]=> float(6.4031242374328) 
    [3]=> float(9.8488578017961) 
    [4]=> float(6.0827625302982) 
    [5]=> float(4.3588989435407) 
}

Adding and Removing Array Elements

A lot of your arrays in a program will be dynamic - the values might change while the program is running. For example, you might be keeping a list of items the user want's to purchase from an on-line store, and you would want to be able to add items to the list and possibly even remove items from the list (if the user changes his/her mind).

Adding Elements

As mentioned earlier, you can add an element to an array that doesn't use sequential numeric indexes easily:

$myGrades["SYST10049"] = 99.0;

This will automatically add a new element to the end of the array, using the key "SYST28043" and the value 99.0.

If the array uses a sequential numerical index, you saw earlier how a statement such as

$languages[] = "Delphi";

will also add a new element to the end of an array.

If an array with numeric indexes such as:

$example = [
    1 => "foo",
    2 => "bar",
    3 => "yay"
];

If you were to add two new elements like this:

$example[7] = "woo";
$example[] = "bbq";
echo "<pre>";
var_dump($example);
echo "</pre>";

The output of displaying the $example array is:

array(5) { 
    [1]=> string(3) "foo" 
    [2]=> string(3) "bar" 
    [3]=> string(3) "yay" 
    [7]=> string(3) "woo" 
    [8]=> string(3) "bbq" 
}

Note that there are no elements 4, 5, and 6. Also note that the value "bbq" is added to element 8. When using empty [] as the index to add a new element, it is always added at the highest index + 1.

Removing Elements

The unset() function can be used to remove an element from an array. Note that unset() does not adjust the array indexes. This example demonstrates that when you remove an element from the $example array, the rest of the elements don't shift to fill in the empty space:

<?
    $example = [
        1 => "foo",
        2 => "bar",
        3 => "yay",
        4 => "wee"
     ];
    unset($example[2]);
    var_dump($example);
?>

Output:

array(4) { 
        [1]=> string(3) "foo" 
        [3]=> string(3) "yay" 
        [4]=> string(3) "wee" 
}

If you're familar with stack and queue operations such as push/pop/shift/unshift, PHP has methods for these:

array_push(arrayName, element, element...) will add one or more elements to the end of an array.

$variable = array_pop(arrayName)
remove the last element in the array and store it in $variable. You can ignore the return value if you don't need to save it.

$variable = array_shift(arrayName)
removes the item from the beginning of the array and stores it in $variable. You can ignore the return value if you don't need to save it.

array_unshift(arrayName, element, element...)
adds one or more elements to the beginning of the array.

If the array uses sequential, numeric indexes, the array elements will be moved to fit any new element or to fill any space left by a removed element. Otherwise, the elements' positions are unaffected.

Example, note only numeric indexes:

<?
    $food = ["chocolate", "cheese"];
    var_dump($food);
    array_push($food, "strawberries");  // add strawberries, inefficient
    echo "<br>";
    var_dump($food);
    array_shift($food); // remove chocolate
    echo "<br>";
    var_dump($food);
    array_unshift($food, "bacon", "eggs"); // add bacon, eggs
    echo "<br>";
    var_dump($food);
    array_pop($food); // remove strawberries
    echo "<br>";
    var_dump($food);
?>

Output:

array(2) { 
    [0]=> string(9) "chocolate" 
    [1]=> string(6) "cheese" 
}
array(3) { 
    [0]=> string(9) "chocolate" 
    [1]=> string(6) "cheese" 
    [2]=> string(12) "strawberries" 
}
array(2) { 
    [0]=> string(6) "cheese" 
    [1]=> string(12) "strawberries" 
}
array(4) { 
    [0]=> string(5) "bacon" 
    [1]=> string(4) "eggs" 
    [2]=> string(6) "cheese"
    [3]=> string(12) "strawberries" 
}
array(3) { 
    [0]=> string(5) "bacon" 
    [1]=> string(4) "eggs" 
    [2]=> string(6) "cheese"
}

Array Operators

Some operators can be used to perform operations on arrays:

Array Operators
Operation Description
+ Union
== Equality
=== Identical
!= or <> Inequality
!== Not Identical

The Union operator will result in the union of the left-hand and right-hand array operands. If there are duplicate keys/indexes, the left-hand elements will be used and the right-hand elements will be ignored:

<?
$bigRooms = [
  "j222" => 40,
  "j224" => 42,
  "j318" => 38,
  "j324" => 42,
  "j322" => 40
];
$labs = [
  "j220" => 22,
  "j222" => 20,
  "j320" => 22,
  "j322" => 22
 ];
$rooms = $bigRooms + $labs;
var_dump($rooms);
?>

Output:

array(7) { 
    ["j222"]=> int(40) 
    ["j224"]=> int(42) 
    ["j318"]=> int(38) 
    ["j324"]=> int(42) 
    ["j322"]=> int(40) 
    ["j220"]=> int(22) 
    ["j320"]=> int(22) 
}

The third array $rooms contains the seven unique elements between the two arrays $bigRooms and $labs. Notice that the duplicates occur with the $bigRooms values: j222 is listed with the value 40, not 20; j322 is listed with the value 40, not 22.

The Equality operator will return true if both the left-hand and right-hand array operands have the same keys/indexes and values:

<?
    $smallRooms = [
      "j220" => 22,
      "j320" => 20,
      "j222" => 42,
      "j322" => 20
    ];
    $labs = [
      "j220" => 22,
      "j222" => 42,
      "j320" => 20,
      "j322" => 20
     ];
    var_dump($smallRooms == $labs);
    $smallRooms["j222"] = 40;
    echo "<br>";
    var_dump($smallRooms == $labs);
?>

Our output shows that despite the array elements being in a different order in each array, the two arrays are considered equal until we change one of the array values:

bool(true)
bool(false)

The Identity operator only returns true if both arrays have the exact same key-value pairs in the exact same order:

<?
    $smallRooms = [
      "j220" => 22,
      "j320" => 20,
      "j222" => 42,
      "j322" => 20
    ];
    $labs = [
      "j220" => 22,
      "j320" => 20,
      "j222" => 42,
      "j322" => 20
     ];
    var_dump($smallRooms === $labs);
    $labs = [
      "j222" => 42,
      "j220" => 22,
      "j320" => 20,
      "j322" => 20
     ];
    echo "<br>";
    var_dump($smallRooms === $labs);
?>

Output:

bool(true)
    bool(false)

Array Functions

There are several functions you can use when working with arrays. We don't have time to cover all of them, so make sure you take the time to browse through them using the link in the box up above. Here are some you'll find useful in these tutorials. Be sure to check the manual for each function and try out some examples.

Exercises

1. Write a program that creates an array called $primes that contains all the prime numbers from 1 to 50. Display the array on the page in the following format:

2 3 5 7 11
13 17 19 23 29 
31 37 41 43 47
53 59 61 67 71 
73 79 83 89 97

Your values are displayed inside a <pre> element in 5 rows of 5 values each.

2. Write program that creates a single array for the following web page data:

Lesson File Name
Introduction intro.html
Lesson 1 lesson1.html
Lesson 2 lesson2.html
Mid Term Review mtReview.html
Lesson 3 lesson3.html
Case Study case.html
Final Review final.html

After hard-coding the array, display the data as a set of links in an un-ordered list like you see below:

Lessons:

3. In PHP, a two-dimensional array is an array where every element is another array. For example:

$twoDimArray = [ [2, 4, 6], [3, 6, 9] ];
var_dump($twoDimArray);
array(2) { 
    [0]=> array(3) { 
        [0]=> int(2) 
        [1]=> int(4) 
        [2]=> int(6) 
    } 
    [1]=> array(3) { 
        [0]=> int(3) 
        [1]=> int(6) 
        [2]=> int(9) 
    } 
}

Write a program that hard-codes a two-dimensional array that contains information about sales people according to the following table:

Sales Person ID Sales Made Commission Rate
smithsal 1244.59 .025
patelgur 2199.02 .05
ngsherry 2014.50 .05
leclerkj 998.90 .035

Write the code that does the following:

  1. Create a two-dimensional array containing the data in the sales table.
    • The key is the sales person's ID
    • The value is an array where the first element is the sales made and the second element is the commission rate
  2. Iterate through the array and for each sales person, calculate the commission earned (sales made * commission rate)
  3. Output an HTML table that displays the sales person ID in one column and the commission earned in the second column.
a table with each sales person, the commission earned from top to bottom is 31.11, 109.95, 100.73, and 34.96
The output for the Sales program

4. Without using a loop, use array functions to calculate the average of an array.