facebook google plus twitter
Webucator's Free PHP Tutorial

Lesson: Arrays

Welcome to our free PHP tutorial. This tutorial is based on Webucator's Introduction to PHP Training course.

Up to this point, we have dealt only with variables that store single values, called scalar variables. In this lesson, we will be covering arrays. Arrays are variables that store sets of values.

Lesson Goals

  • To work with indexed arrays.
  • To work with associative arrays.
  • To work with two-dimensional arrays.
  • To work with array-manipulation functions.

Indexed Arrays

Indexed arrays are similar to tables with a single column. An indexed array can contain zero or more elements. In PHP, like in many programming languages, the first element of an array is in the "zeroeth" position. An array with no elements has a zero length.

Initializing Arrays

Arrays are initialized with the array() function, which can take a list of comma-delimited values that become the elements in the new array. The following code initializes a zero-length array and then adds four elements to the array:

$beatles = array();
$beatles[0] = 'John';
$beatles[1] = 'Paul';
$beatles[2] = 'George';
$beatles[3] = 'Ringo';

The $beatles array could also be created in a single line by passing values into the array() function:

$beatles = array('John', 'Paul', 'George', 'Ringo');

But perhaps the simplest way of creating an array is to use square brackets. This is known as the short array syntax:

$beatles = ['John', 'Paul', 'George', 'Ringo'];

Appending to an Array

If you know how many elements are in an array, you can append to the array by specifying the index. For example, you could append a fifth Beatle to the $beatles array like this:

$beatles[4] = 'Nat';

However, often you won't know how many elements are in an array. Although you can easily figure this out, doing so requires an extra step. PHP provides an easy way of appending to an array of any length. Simply leave out the index. You could add a sixth Beatle to the $beatles array like this:

$beatles[] = 'Connie';

Now, $beatles[5] will contain 'Connie'.

Reading from Arrays

Reading from arrays is just a matter of pointing to a specific index or key.

echo $beatles[2]; // outputs George

Looping through Arrays

The following code will loop through the entire $beatles array outputting each element to the browser.

foreach ($beatles as $beatle) {
  echo "$beatle<br>";
}

The above code snippets are combined in the following example:

Code Sample:

Arrays/Demos/indexed-arrays.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="../../static/styles/normalize.css">
<link rel="stylesheet" href="../../static/styles/styles.css">
<title>Indexed Arrays</title>
</head>
<body>
<main>
  <h1>Indexed Arrays</h1>
  <?php
    $beatles = ['John', 'Paul', 'George', 'Ringo'];
    
    echo "<p>$beatles[2]</p>"; //outputs George
    
    $beatles[4] = 'Nat';
    echo "<p>$beatles[4]</p>"; //outputs Nat
    
    $beatles[] = 'Connie';
    echo "<p>$beatles[5]</p>"; //outputs Connie
  ?>
  <hr>
  <ol>
  <?php
    foreach ($beatles as $beatle) {
      echo "<li>$beatle</li>";
    }
  ?>
  </ol>
</main>
</body>
</html>

Code Explanation

Navigate to http://localhost:8888/Webucator/php/Arrays/Demos/indexed-arrays.php to see this page in your browser: Indexed Arrays

Working with Indexed Arrays

Duration: 10 to 15 minutes.

In this exercise, you will use arrays to create a table with a single column that lists all your favorite colors. As shown in the screenshot below, the background of each table row should be the same as the color named in the row: Color Table

Color Names

See https://developer.mozilla.org/en-US/docs/Web/CSS/color_value for a list of color names.

  1. Open Arrays/Exercises/color-table.php for editing.
  2. Create an array that holds your favorite colors.
  3. Inside of the open and close <tbody> tags, loop through the array outputting a table row for each element.
  4. Test your solution in a browser.

Solution:

Arrays/Solutions/color-table.php
---- C O D E   O M I T T E D ----
  <h1>Color Table</h1>
  <?php
    $favColors = ['blanchedalmond',
                  'lightsalmon',
                  'burlywood',
                  'lemonchiffon',
                  'hotpink',
                  'papayawhip'];
  ?>
  <table>
    <thead>
      <tr>
        <th>Color</th>
      </tr>
    </thead>
    <tbody>
      <?php
        foreach ($favColors as $color) {
          echo "<tr style='background-color:$color'>
                  <td>$color</td>
                </tr>";
        }
      ?>
    </tbody>
  </table>
---- C O D E   O M I T T E D ----

Associative Arrays

Whereas indexed arrays are indexed numerically, associative arrays are indexed using names. For example, instead of Ringo being indexed as 3, he could be indexed as "drummer".

Initializing Associative Arrays

Like with indexed arrays, we can initialize a zero-length associative array and then add elements:

$beatles = array();
$beatles['singer1'] = 'Paul';
$beatles['singer2'] = 'John';
$beatles['guitarist'] = 'George';
$beatles['drummer'] = 'Ringo';

Or the array could be created using the double-arrow operator (=>) in a single step as follows:

$beatles = array('singer1' => 'John',
                  'singer2' => 'Paul',
                  'guitarist' => 'George',
                  'drummer' => 'Ringo');

Like with indexed arrays, you can use the short array syntax to create associative arrays:

$beatles = ['singer1' => 'John',
            'singer2' => 'Paul',
            'guitarist' => 'George',
            'drummer' => 'Ringo'];

Reading from Associative Arrays

Reading from associative arrays is as simple as reading from indexed arrays:

echo $beatles['drummer']; // outputs Ringo

Looping through Associative Arrays

The following code will loop through the entire $beatles array outputting each element and its key to the browser:

foreach ($beatles as $key => $beatle) {
  echo "<strong>$key:</strong> $beatle<br>";
}

The above code snippets are combined in the following example:

Code Sample:

Arrays/Demos/associative-arrays.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="../../static/styles/normalize.css">
<link rel="stylesheet" href="../../static/styles/styles.css">
<title>Associative Arrays</title>
</head>
<body>
<main>
  <h1>Associative Arrays</h1>
  <?php
  $beatles = ['singer1' => 'John',
              'singer2' => 'Paul',
              'guitarist' => 'George',
              'drummer' => 'Ringo'];

  echo $beatles['drummer']; // outputs Ringo
  ?>
  <hr>
  <ol>
    <?php
    foreach ($beatles as $key => $beatle) {
      echo "<li><strong>$key:</strong> $beatle</li>";
    }
    ?>
  </ol>
</main>
</body>
</html>

Code Explanation

Navigate to http://localhost:8888/Webucator/php/Arrays/Demos/associative-arrays.php to see this page in your browser: Associative Arrays

Working with Associative Arrays

Duration: 10 to 15 minutes.

In this exercise, you will use arrays to create a table with two columns that lists all your favorite colors and their hexadecimal equivalents. The background of each table row should be the same as the color named in the row as shown in the screenshot below:Color Table 2

Color Names

See https://developer.mozilla.org/en-US/docs/Web/CSS/color_value for a list of color names.

  1. Open Arrays/Exercises/color-table-2.php for editing.
  2. Create an associative array that holds color hex codes indexed by their color names.
  3. Inside of the open and close <tbody> tags, write code to loop through the array outputting a table row with two columns for each element in the array.
  4. Test your solution in a browser.

Solution:

Arrays/Solutions/color-table-2.php
---- C O D E   O M I T T E D ----
  <h1>Color Table</h1>
  <?php
    $favColors = [
      'blanchedalmond' => '#ffebcd',
      'lightsalmon' => '#ffa07a',
      'burlywood' => '#deb887',
      'lemonchiffon' => '#fffacd',
      'hotpink' => '#ff69b4',
      'papayawhip' => '#ffefd5'
    ];
  ?>

  <table>
    <thead>
      <tr>
        <th>Color Name</th>
        <th>Hex Code</th>
      </tr>
    </thead>
    <tbody>
      <?php
        foreach ($favColors as $key => $item) {
          echo "<tr style='background-color:$key'>
                  <td>$key</td>
                  <td>$item</td>
                </tr>";
        }
      ?>
    </tbody>
  </table>
---- C O D E   O M I T T E D ----

Superglobal Arrays

The superglobal arrays are associative arrays. The file below outputs all the contents of the superglobal arrays using foreach loops. Don't worry about the session_start() statement at the top. We'll cover that in detail later in the course.

Code Sample:

Arrays/Demos/superglobals.php
---- C O D E   O M I T T E D ----
  <h1>Superglobal Arrays</h1>
  <h2>$_COOKIE</h2>
  <ol>
    <?php
      foreach ($_COOKIE as $key => $item) {
        echo "<li><strong>$key:</strong> $item</li>";
      }
    ?>
  </ol>
  <hr>
  <h2>$_ENV</h2>
  <ol>
  <?php
      foreach ($_ENV as $key => $item) {
        echo "<li><strong>$key:</strong> $item</li>";
      }
    ?>
  </ol>
  <hr>
  <h2>$_FILES</h2>
  <ol>
    <?php
      foreach ($_FILES as $key => $item) {
        echo "<li><strong>$key:</strong> $item</li>";
      }
    ?>
  </ol>
  <hr>
  <h2>$_GET</h2>
  <ol>
    <?php
      foreach ($_GET as $key => $item) {
        echo "<li><strong>$key:</strong> $item</li>";
      }
    ?>
  </ol>
  <hr>
  <h2>$_POST</h2>
  <ol>
    <?php
      foreach ($_POST as $key => $item) {
        echo "<li><strong>$key:</strong> $item</li>";
      }
    ?>
  </ol>
  <hr>
  <h2>$_REQUEST</h2>
  <ol>
    <?php
      foreach ($_REQUEST as $key => $item) {
        echo "<li><strong>$key:</strong> $item</li>";
      }
    ?>
  </ol>
  <hr>
  <h2>$_SESSION</h2>
  <ol>
    <?php
      foreach ($_SESSION as $key => $item) {
        echo "<li><strong>$key:</strong> $item</li>";
      }
    ?>
  </ol>
  <hr>
  <h2>$_SERVER</h2>
  <ol>
    <?php
      foreach ($_SERVER as $key => $item) {
        echo "<li><strong>$key:</strong> $item</li>";
      }
    ?>
  </ol>
---- C O D E   O M I T T E D ----

Code Explanation

Navigate to http://localhost:8888/Webucator/php/Arrays/Demos/superglobals.php to see this page in your browser. Note that many of these superglobal arrays will be empty. For example, the $_POST and $_GET arrays will be empty because no data has been posted via a form or sent via the query string. If you want to populate $_GET with some value, add a query string with a parameter, like this:

superglobals.php?number=42

Then you should see the following: Superglobals with $_GET populated

Multi-dimensional Arrays

In PHP, multi-dimensional arrays are arrays that contain arrays (that may contain arrays, and so on). You can think of a two-dimensional array as a table with the outer array containing the rows and the inner arrays containing the data cells in those rows. For example, a two-dimensional array called $rockBands could contain the names of the bands and some of the songs that they sing. Below is a grid that represents such a two-dimensional array:

Rock Band Song1 Song2 Song3
Beatles Love Me Do Hey Jude Helter Skelter
Rolling Stones Waiting on a Friend Angie Yesterday's Papers
Eagles Life in the Fast Lane Hotel California Best of My Love

The following code creates this two-dimensional array. The internal arrays are highlighted. Note that the header row is not included:

$rockBands = [
  [
    'Beatles',
    'Love Me Do',
    'Hey Jude',
    'Helter Skelter'
  ],
  [
    'Rolling Stones',
    'Waiting on a Friend',
    'Angie',
    'Yesterday\'s Papers'
  ],
  [
    'Eagles',
    'Life in the Fast Lane',
    'Hotel California',
    'Best of My Love'
  ]
];

Reading from Two-dimensional Arrays

To read an element from a two-dimensional array, you must first identify the index of the "row" and then identify the index of the "column." For example, the song "Waiting on a Friend" is in row 1, column 1, so it is identified as $rockBands[1][1]. Remember that the first row is row 0 and the first column is column 0.

Looping through Two-dimensional Arrays

To loop through a two-dimensional array, you need to nest one loop inside of another. The following code will create an HTML table from our two-dimensional array:

<table>
  <thead>
    <tr>
      <th>Rock Band</th>
      <th>Song 1</th>
      <th>Song 2</th>
      <th>Song 3</th>
    </tr>
  </thead>
  <tbody>
    <?php
    foreach($rockBands as $rockBand) {
      // $rockBand contains an inner array
      echo "<tr>";
      foreach($rockBand as $item) {
        echo "<td>$item</td>";
      }
      echo "</tr>";
    }
    ?>
  </tbody>
</table>

The above code snippets are combined in the following example to output a Rock Bands table:

Code Sample:

Arrays/Demos/two-dimensional-arrays.php
---- C O D E   O M I T T E D ----
<h1>Two-Dimensional Arrays</h1>
<?php
$rockBands = [
  ['Beatles',
    'Love Me Do',
    'Hey Jude',
    'Helter Skelter'],
  ['Rolling Stones',
    'Waiting on a Friend',
    'Angie',
    'Yesterday\'s Papers'],
  ['Eagles',
    'Life in the Fast Lane',
    'Hotel California',
    'Best of My Love']
];
?>
<table>
  <thead>
    <tr>
      <th>Rock Band</th>
      <th>Song 1</th>
      <th>Song 2</th>
      <th>Song 3</th>
    </tr>
  </thead>
  <tbody>
    <?php
    foreach($rockBands as $rockBand) {
      // $rockBand contains an inner array
      echo '<tr>';
      foreach($rockBand as $item)   {
        echo "<td>$item</td>";
      }
      echo '</tr>';
    }
    ?>
  </tbody>
</table>
---- C O D E   O M I T T E D ----

Code Explanation

Two-dimensional Associative Arrays

The two-dimensional array above would be better expressed as an associative array to clarify the relationship between the rock band and the songs. The following demo shows how to do this:

Code Sample:

Arrays/Demos/two-dimensional-associative-arrays.php
---- C O D E   O M I T T E D ----
<h1>Two-Dimensional Associative Arrays</h1>
<?php
$rockBands = [
  'Beatles' => ['Love Me Do',
                'Hey Jude',
                'Helter Skelter'],
  'Rolling Stones' => ['Waiting on a Friend',
                'Angie',
                'Yesterday\'s Papers'],
  'Eagles' => ['Life in the Fast Lane',
                'Hotel California',
                'Best of My Love']
];
?>
<table>
  <thead>
    <tr>
      <th>Rock Band</th>
      <th>Song 1</th>
      <th>Song 2</th>
      <th>Song 3</th>
    </tr>
  </thead>
  <tbody>
    <?php
    foreach($rockBands as $rockBand => $songs) {
      // $rockBand contains an inner array
      echo "<tr><td><strong>$rockBand:</strong></td>";
      foreach($songs as $song)   {
        echo "<td>$song</td>";
      }
      echo '</tr>';
    }
    ?>
  </tbody>
</table>
---- C O D E   O M I T T E D ----

Code Explanation

Non-tabular Multi-dimensional Arrays

While it is helpful to think of a two-dimensional array as a table, you should be aware that an array can contain subarrays of different lengths and even contain items of different types. To illustrate, let's look again at our $beatles array:

$beatles = ['singer1' => 'John',
            'singer2' => 'Paul',
            'guitarist' => 'George',
            'drummer' => 'Ringo'];

The singer1 and singer2 keys are problematic. Imagine we were storing data on a lot of rock bands, some of which only had one singer and others which had several. Imagine then that you are tasked with writing code to list all of the singers from the bands. You wouldn't know which bands had keys for 'singer2', 'singer3', etc.

Now take a look at a better way of storing our Beatles data:

$beatles = [
  'singers' => ['Paul', 'John'],
  'guitarist' => 'George',
  'drummer' => 'Ringo'
];

With this code, you can easily list all the singers, simply by looping through the $beatles['singers'] array:

foreach ($beatles['singers'] as $singer) {
  echo "$singer<br>";
}

Array Manipulation Functions

There are many built-in array-manipulation functions in PHP. The full list is at https://www.php.net/manual/en/ref.array.php.

In an upcoming exercise, you will practice working with these functions. In doing so, you will need to read the documentation at php.net. One important thing to know about a function is whether it modifies the original array that is passed in in place or creates and returns a new array (or some other object). If the parameter is passed in by reference, then it will modify the passed-in array. If it passed in by value, then it will not modify the passed-in array. The documentation will generally explicitly tell you which it will do, but you can also tell from the function signature. The following two signatures illustrate the difference: Function Signature: array_reverse() Function Signature: sort() Notice that array_reverse() receives the array by value, meaning it won't change the original array, and returns a new array. The sort() function, on the other hand, receives the array by reference (that's what the ampersand (&) does) and returns a boolean indicating whether or not it successfully modified the original array.

in_array() Function

The in_array() function is used to check if a value is found in an array. For example:

$fruit = ['apple', 'banana', 'pear'];
$foodItem = 'apple';
if (in_array($foodItem, $fruit)) {
  echo "$foodItem is a fruit.";
}

Array Practice

Duration: 25 to 40 minutes.

In this exercise, you will practice using PHP's built-in array functions and you will write a couple of your own. You will likely need to read the documentation at php.net to see how some of these functions work. You should test your solutions as you work.

  1. Open Arrays/Exercises/arrays.php for editing.
  2. The file contains the following code:
    1. An outputArray() user-defined function that outputs an unordered list of the keys and values in an array.
    2. A $numbers array.
    3. A $colors array.
    4. Beneath those array definitions, it outputs those arrays using the outputArray() function:Original ArraysYour job is to write code that uses array functions.
  3. array_reverse() - Returns a new array in reverse order. Prove it with both arrays. This one is done for you.
  4. sort() - Sorts an array in place and re-indexes. Prove it with the $numbers array. This one is done for you.
  5. asort() - Sorts an associative array on its values, keeping the key-value pairs together. Prove it with the $colors array.
  6. ksort() - Sorts an associative array on its keys, keeping the key-value pairs together. Prove it with the $colors array.
  7. rsort() - Sorts an array in reverse order in place and re-indexes. Prove it with the $numbers array.
  8. arsort() - Sorts an associative array on its values in reverse order, keeping the key-value pairs together. Prove it with the $colors array.
  9. krsort() - Sorts an associative array on its keys in reverse order, keeping the key-value pairs together. Prove it with the $colors array.
  10. shuffle() - Randomly shuffles an array and re-indexes. Prove it with the $numbers array.
  11. array_keys() - Returns the keys of an associative array as an indexed array. Prove it with the $colors array.
  12. count() - Counts the number of elements in an array. Prove it with both arrays.
  13. explode() - Splits a string on a string to create an array. A string of spells is provided. Split it into an array on ", " (a comma followed by a space) and assign the result to $spellsArray.
  14. implode() - Joins an array on a string to create a string. Join the array you created in the last step on " - " (a space, followed by a dash, followed by a space) and assign the result to $spells.
  15. is_array() - Checks if the passed-in argument is an array.
    1. Write a function called outputIsArray() that takes one parameter:
      1. $arr
    2. If $arr is an array, the function should output:
      <p>That is an array:</p>
      And then it should pass the array to outputIsArray().
    3. If $arr is not an array, the function should output:
      <p>That is not an array.</p>
    4. Pass $spellsArray to outputIsArray().
    5. Pass $spells to outputIsArray().
  16. array_key_exists() - Checks if an array contains a key.
    1. Write a function called hasKey() that takes two parameters:
      1. $key
      2. $arr
    2. If $key is found in $arr, the function should output:
      <p>$key is in that array.</p>
      And then it should pass the array to outputIsArray().
    3. If $key is not found in $arr, the function should output:
      <p>$key is in not that array.</p>
    4. Use hasKey() to check if these colors are in the $colors array:
      1. hotpink
      2. olivedrab.
  17. array_walk() - Applies a function to every element in an array. There is already a createButton() function in the exercise file. Using that function and array_walk(), create buttons for all the colors in the $colors array.

Solution:

Arrays/Solutions/arrays.php
---- C O D E   O M I T T E D ----
  <h1>Practice with Arrays</h1>
  <?php
    function outputArray($arr) {
      echo '<ul>';
      foreach ($arr as $key => $a) {
        echo "<li><strong>$key</strong>: $a</li>";
      }
      echo '</ul>';
      echo '<hr>';
    }
    $numbers = [5, 7, 11, 3, -5];

    $colors = [
      'blanchedalmond' => '#ffebcd',
      'lightsalmon' => '#ffa07a',
      'burlywood' => '#deb887',
      'lemonchiffon' => '#fffacd',
      'hotpink' => '#ff69b4',
      'papayawhip' => '#ffefd5'
    ];

    echo '<h2>Original Arrays</h2>';
    echo '<h3>$numbers</h3>';
    outputArray($numbers);
    echo '<h3>$colors</h3>';
    outputArray($colors);
    
    echo '<h2>array_reverse()</h2>';
    echo '<p>Returns a new array in reverse order.</p>';
    $reversedNumbers = array_reverse($numbers);
    $reversedColors = array_reverse($colors);
    outputArray($reversedNumbers);
    outputArray($reversedColors);
    
    echo '<h2>sort()</h2>';
    echo '<p>Sorts on value and re-indexes.</p>';
    sort($numbers);
    outputArray($numbers);

    echo '<h2>asort()</h2>';
    echo '<p>Sorts on value. Keeps key-value pairs together.</p>';
    asort($colors);
    outputArray($colors);
    
    echo '<h2>ksort()</h2>';
    echo '<p>Sorts on key. Keeps key-value pairs together.</p>';
    ksort($colors);
    outputArray($colors);
    
    echo '<h2>rsort()</h2>';
    echo '<p>Sorts in reverse on value and re-indexes.</p>';
    rsort($numbers);
    outputArray($numbers);

    echo '<h2>arsort()</h2>';
    echo '<p>Sorts in reverse on value. Keeps key-value pairs.</p>';
    arsort($colors);
    outputArray($colors);
    
    echo '<h2>krsort()</h2>';
    echo '<p>Sorts in reverse on key. Keeps key-value pairs.</p>';
    krsort($colors);
    outputArray($colors);
    
    echo '<h2>shuffle()</h2>';
    echo '<p>Randomly shuffles array and re-indexes. ';
    shuffle($numbers);
    outputArray($numbers);
    
    echo '<h2>array_keys()</h2>';
    echo '<p>Returns keys as indexed array.</p>';
    $colorKeys = array_keys($colors);
    outputArray($colorKeys);
    
    echo '<h2>count()</h2>';
    echo '<p>Counts the number of elements in an array.</p>';
    echo 'Number of numbers: ' . count($numbers);
    echo '<br>';
    echo 'Number of colors: ' . count($colors);

    echo '<h2>explode()</h2>';
    echo '<p>Splits a string on a string to create an array.';
    $spells = 'Riddikulus, Obliviate, Avada Kedavra, Expelliarmus';
    $spellsArray = explode(', ', $spells);
    outputArray($spellsArray);

    echo '<h2>implode()</h2>';
    echo '<p>Joins an array on a string to create a string.</p>';
    $spells = implode(' - ', $spellsArray);
    echo $spells;

    echo '<h2>is_array()</h2>';
    echo '<p>Checks if a passed-in argument is an array.</p>';

    function outputIsArray($arr) {
      if (is_array($arr)) {
        echo '<p>That is an array:</p>';
        outputArray($arr);
      } else {
        echo '<p>That is not an array.</p>';
      }
    }
    
    echo outputIsArray($spellsArray);
    echo outputIsArray($spells);

    echo '<h2>array_key_exists()</h2>';
    echo '<p>Checks if an array contains a key.</p>';

    function hasKey($key, $arr) {
      if (array_key_exists($key, $arr)) {
        echo "<p>$key is in that array.</p>";
      } else {
        echo "<p>$key is not in that array.</p>";
      }
    }
    
    echo hasKey('hotpink', $colors);
    echo hasKey('olivedrab', $spellsArray);

  
    echo '<h2>array_walk()</h2>';

    function createButton($color, $text) {
      echo "<button style='background-color:$color'
        onclick='document.body.style.backgroundColor=\"$color\";'>
          $text</button>";
    }
    
    array_walk($colors, createButton);
  ?>
---- C O D E   O M I T T E D ----