Core PHP

PHP Lesson 8: Simple Array Usage

Overview

The purpose of this lesson is to introduce the concept of arrays and to show the various syntax used for initializing, filling them with data, and then accessing that data from them. An array is object that holds a collection of data items. In PHP, arrays can hold multiple types of data items, unlike some other languages.

Creating and Filling an Array

Our first program shows the basic method for creating an array, filing it, and accessing the data elements within the array. To create the array, we call the array() function. This function returns an empty array that we can fill with data; the array is empty because nothing was passed into the function. Next, we call the array_push() function 12 times to add the 12 Fruits of the Holy Spirit into the array. Then, to demonstrate that 12 elements have been added to the array, we print out the result by calling the count() function on the array. Finally, we access each element of the array by using the [] operator with the indices 0 through 11 (array indices start at 0 by default) and putting the result into an unordered list for printing.

Prog1.php

<!DOCTYPE html>
<html>
  <head>
    <title>XoaX.net PHP</title>
  </head>
  <body>
<?php
  $saFruitsOfTheSpirit = array();
  array_push($saFruitsOfTheSpirit, "charity");
  array_push($saFruitsOfTheSpirit, "joy");
  array_push($saFruitsOfTheSpirit, "peace");
  array_push($saFruitsOfTheSpirit, "patience");
  array_push($saFruitsOfTheSpirit, "kindness");
  array_push($saFruitsOfTheSpirit, "goodness");
  array_push($saFruitsOfTheSpirit, "generosity");
  array_push($saFruitsOfTheSpirit, "gentleness");
  array_push($saFruitsOfTheSpirit, "faithfulness");
  array_push($saFruitsOfTheSpirit, "modesty");
  array_push($saFruitsOfTheSpirit, "self-control");
  array_push($saFruitsOfTheSpirit, "chastity");

  echo "<p>Array Size: ".count($saFruitsOfTheSpirit)."</p>";

  echo "<ul>";
  echo "  <li>".$saFruitsOfTheSpirit[0]."</li>";
  echo "  <li>".$saFruitsOfTheSpirit[1]."</li>";
  echo "  <li>".$saFruitsOfTheSpirit[2]."</li>";
  echo "  <li>".$saFruitsOfTheSpirit[3]."</li>";
  echo "  <li>".$saFruitsOfTheSpirit[4]."</li>";
  echo "  <li>".$saFruitsOfTheSpirit[5]."</li>";
  echo "  <li>".$saFruitsOfTheSpirit[6]."</li>";
  echo "  <li>".$saFruitsOfTheSpirit[7]."</li>";
  echo "  <li>".$saFruitsOfTheSpirit[8]."</li>";
  echo "  <li>".$saFruitsOfTheSpirit[9]."</li>";
  echo "  <li>".$saFruitsOfTheSpirit[10]."</li>";
  echo "  <li>".$saFruitsOfTheSpirit[11]."</li>";
  echo "</ul>";
?>
  </body>
</html>
 
 

Output for Prog1.php

 

Indexed and Associative Arrays

This second program introduces a new method for adding elements to an array and associative arrays. In the previous program, we use the array_push() function to put values into the array. In this program, we assign value to the entries of the array, such as $saMarks[1] = "Holy", which sets the second entry at the index 1 to the value "Holy". This is the same as calling array_push(), as far as adding an element, except that it adds the element at a specific index, rather than the next available one. To display the array and its entries, we call the print_r($saMarks) function put it inside a pre element to preserve the formatting.

The second array is called $saFathers and it is an associative array. In an associative array, the values of the array are indexed by strings, rather than integers. So, when we write $saFathers['Abraham'] = "Terah";, we set the value at index 'Abraham' to the value "Terah". Again, we call print_r($saMarks) to show the final resulting array.

Prog2.php

<!DOCTYPE html>
<html>
  <head>
    <title>XoaX.net PHP</title>
  </head>
  <body>
<?php
$saMarks = array();
$saMarks[0] = "One";
$saMarks[1] = "Holy";
$saMarks[2] = "Catholic";
$saMarks[3] = "Apostolic";

echo "<p>The third mark of the Church is ".$saMarks[2].".</p>";

echo "<pre>";
print_r($saMarks);
echo "</pre>";

$saFathers = array();
$saFathers['Abraham'] = "Terah";
$saFathers['Isaac'] = "Abraham";
$saFathers['Jacob'] = "Isaac";
$saFathers['Esau'] = "Isaac";
$saFathers['Joseph'] = "Jacob";
$saFathers['Levi'] = "Jacob";

echo "<p>The father of Jacob is ".$saFathers['Jacob'].".</p>";

echo "<pre>";
print_r($saFathers);
echo "</pre>";
?>
  </body>
</html>
 
 

Output for Prog2.php

 

Array Initialization Methods

Our third program, demonstrates how initialize an array with elements and various mathods for adding elemetns to arrays. First, we initialize our first array, $saMarks, by passing the strings "One" and "Holy" in the array function; this has the efect of creating an array with those two strings already in it at the indicies 0 and 1.

Then we add "Catholic" to the array by assigning it to the next entry in the array, namely 2. Note that we can assign any index a value. If we had assigned "Catholic" to the index 0 or 1, it would have written over the value already at the index. If we had assigned "Catholic" to the index 10, it would have skip over left the values 2 though 9 and left them empty.

After this, we add "Apostolic" to the array via the array_push() function. This function adds value at the next highest index. In this case, it adds "Apostolic" at the index 3. If "Catholic" had been set to the index 10, then "Apostolic" would have been added at the index 11, even if the indices 2 through 9 were not assigned.

The array, $saFathers, is an associative array, that we intialized with three indices and their associated values. To do this, we use the arrow operator => to associate each index with a value. Then we add three more values at their associated indices. We call print_r() on each array to display their contents.

Prog3.php

<!DOCTYPE html>
<html>
  <head>
    <title>XoaX.net PHP</title>
  </head>
  <body>
<?php
$saMarks = array("One", "Holy");
$saMarks[2] = "Catholic";
array_push($saMarks, "Apostolic");

echo "<pre>";
print_r($saMarks);
echo "</pre>";

$saFathers = array('Abraham' => 'Terah',
                    'Isaac' => 'Abraham',
                    'Jacob' => 'Isaac');

$saFathers['Esau'] = "Isaac";
$saFathers['Joseph'] = "Jacob";
$saFathers['Levi'] = "Jacob";

echo "<pre>";
print_r($saFathers);
echo "</pre>";
?>
  </body>
</html>
 
 

Output for Prog3.php

 

Mixing Data Types in an Array

Our fourth program shows how we can mix together various indices and values within an array. We begin by initializes the array with the empty bracket operator: []. This creates an empty array and is the same as calling the array() function with no arguments. Then we add the string "theological" at the indicies "faith", "hope", and "love" because these are the theological virtues. Next, we add an array of the four cardinal virtues at the index "cardinal"; this demonstrates that we can add arrays as values within an array. Then we add the string "three" at the index 3; this shows that we can mix numerical indices with string indices in one array. After this, we add the two strings, "automatic0" and "automatic1", by assigning them to an empty index; this has the same effect as calling the array_push() function as we do for "test".

With all of these various values, the array is something of a mess, but we print out array by calling the print_r() function. Finally, we show that we can access the array elements for the array within the array by using a double index: $qaArray["cardinal"][0]

Prog4.php

<!DOCTYPE html>
<html>
  <head>
    <title>XoaX.net PHP</title>
  </head>
  <body>
<?php
$qaArray = [];
$qaArray["faith"] = "theological";
$qaArray["hope"] = "theological";
$qaArray["love"] = "theological";

$qaArray["cardinal"] = ["prudence", "justice", "temperance", "fortitude"];

$qaArray[3] = "three";

$qaArray[] = "automatic0";
$qaArray[] = "automatic1";

array_push($qaArray, "test");

echo "<pre>";
print_r($qaArray);
echo "</pre>";

echo "<p>One of the cardinal virtues is ".$qaArray["cardinal"][0].".</p>";

?>
  </body>
</html>
 
 

Output for Prog4.php

 

Using Bracket Notation

For our last program, we demonstrate that we can initialize both integer-indexed arrays and associative arrays by using the bracket notation, instead of calling the array() function. To do this, we can pass in a set of values to create an array with the default integer indicies, like we do for $saMarks. Otherwise, we can pass in a set of index-value pairs to create an associative arrya as we do for $saFathers. In either case, the bracket functions identically the same as the array() function.

Prog5.php

<!DOCTYPE html>
<html>
  <head>
    <title>XoaX.net PHP</title>
  </head>
  <body>
<?php
$saMarks = ["One", "Holy", "Catholic", "Apostolic"];

echo "<pre>";
print_r($saMarks);
echo "</pre>";

$saFathers = ['Abraham' => 'Terah',
    'Isaac' => 'Abraham',
    'Jacob' => 'Isaac',
    'Esau' => 'Isaac',
    'Joseph' => 'Jacob',
    'Levi' => 'Jacob'];

echo "<pre>";
print_r($saFathers);
echo "</pre>";
?>
  </body>
</html>
 
 

Output for Prog5.php

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.