Arrays in PHP with examples

In PHP, we use an array when we need to store multiple values in a single variable.

How do we create an array in PHP?

We use the "array()" function when we need to create an array in PHP. The syntax of the "array()" function to create an array is as follows:

arrayVariableName = array(item1, item2, item3,..., itemN);

The "array()" can be considered a constructor. "item1", "item2", "item3", and so on. are the items of the array named "arrayVariableName". For example:

$students = array("William", "Edwin", "Lucas", "Julia");

PHP array example

Consider the following PHP code as an example of an array in PHP:

PHP Code
<?php 
   $students = array("William", "Edwin", "Lucas", "Julia");
   print_r($students);
?>
Output
Array ( [0] => William [1] => Edwin [2] => Lucas [3] => Julia )

The "print_r()" function is used to print an array, object, or variable's contents in a human-readable format. It is defined in the next post.

Find the length of an array in PHP

To find the length of an array in PHP, use the "count()" function. For example:

PHP Code
<?php 
   $students = array("William", "Edwin", "Lucas", "Julia");
   $studentsLength = count($students);
   echo $studentsLength;
?>
Output
4

Access array items using the index value in PHP

Because indexing in an array starts with 0, "students[0]" refers to the very first item of the array, which is "William" based on the previously defined array. For example:

PHP Code
<?php 
   $students = array("William", "Edwin", "Lucas", "Julia");
   
   echo "First item: ", $students[0];
   echo "<BR>";
   echo "Second item: ", $students[1];
   echo "<BR>";
   echo "Third item: ", $students[2];
   echo "<BR>";
   echo "Fourth item: ", $students[3];
?>
Output
First item: William
Second item: Edwin
Third item: Lucas
Fourth item: Julia

Another way that we can approach printing the array items is as follows:

PHP Code
<?php 
   $students = array("William", "Edwin", "Lucas", "Julia");
   echo "Items = ". $students[0].", ". $students[1].", ". $students[2].", and ". $students[3];
?>
Output
Items = William, Edwin, Lucas, and Julia

Print all items of an array using a loop in PHP

The previous method, on the other hand, is not recommended because it is not possible to write the array items manually if the items of the array are unknown. Therefore, we need to loop through the array. For example:

PHP Code
<?php 
   $stds = array("William", "Edwin", "Lucas", "Julia");
   
   $sLen = count($stds);
   for($i = 0; $i < $sLen; $i++) {
      echo $stds[$i];
      echo "<BR>";
   }
?>
Output
William
Edwin
Lucas
Julia

All the arrays that are discussed above come under the type "indexed array in PHP". However, there are other two types of arrays available in PHP, which are "associative array" and "multi-dimensional array". So let's discuss these two other types of arrays one by one, starting with the "associative array".

PHP associative array

An associative array in PHP is a type of array where accessing its elements is done through string keys rather than numerical indices. The values, which can be of any data type, including other arrays, are linked to the corresponding keys.

The general form to create an associative array in PHP is as follows:

$myarray array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3',
    ...
);

PHP associative array example

PHP Code
<?php 
   $stds = array(
      'name' => 'Edwin',
      'age' => 26,
      'city' => 'Houston'
   );
   
   echo $stds['name'];
   echo "<BR>";
   
   echo $stds['age'];
   echo "<BR>";
   
   echo $stds['city'];
?>
Output
Edwin
26
Houston

However, we can also use loop to print the items of an associative array. Consider the following PHP code as an example demonstrating the printing of an associative array through a loop.

PHP Code
<?php 
   $stds = array(
      'name' => 'Edwin',
      'age' => 26,
      'city' => 'Houston'
   );
   
   foreach($stds as $k => $v) {
      echo $k . " = " . $v;
      echo "<BR>";
   }
?>
Output
name = Edwin
age = 26
city = Houston

Modify an existing element and add a new key-value pair

We can also update the value of any key that is already available in the PHP associative array. In addition, we can also add new items. Consider the following PHP code as an example demonstrating this concept:

PHP Code
<?php 
   $stds = array(
      'name' => 'Edwin',
      'age' => 26,
      'city' => 'Houston'
   );
   
   echo "<p>Before modification</p>";
   foreach($stds as $k => $v) {
      echo $k . " = " . $v;
      echo "<BR>";
   }
   
   $stds['name'] = 'William';
   $stds['gender'] = 'male';
   
   echo "<hr><p>After modification</p>";
   foreach($stds as $k => $v) {
      echo $k . " = " . $v;
      echo "<BR>";
   }
?>
Output
Before modification

name = Edwin
age = 26
city = Houston

After modification name = William age = 26 city = Houston gender = male

PHP multidimensional array

In PHP, a multi-dimensional array is an array that itself contains another array (or more than one). Multidimensional arrays allow each element to be another array, effectively creating a hierarchy of arrays. For example:

$myarray = array(
    array(1, 2, 3),
    array(4, 5, 6),
    array(7, 8, 9)
);

In this example, $myarray is a two-dimensional array with three sub-arrays, each of which has three integer values.

PHP multidimensional array example

PHP Code
<?php 
   $myarray = array(
   array(1, 2, 3),
   array(4, 5, 6),
   array(7, 8, 9),
   array(10, 11, 12)
   );
   
   for($i=0; $i<4; $i++) {
      for($j=0; $j<3; $j++) {
         echo $myarray[$i][$j];
         echo " ";
      }
      echo "<BR>";
   }
?>
Output
1 2 3
4 5 6
7 8 9
10 11 12

This PHP code creates a 2-dimensional array called $myarray, iterates through its elements, and prints them to the output using two nested for loops.

To represent a 4x3 matrix, the array is initially initialized with four sub-arrays, each containing three integer values.

Starting with the first sub-array and moving row by row, the two for loops are used to iterate over each element of the array. The inner loop iterates over the matrix's columns while the outer loop iterates over the matrix's rows.

The echo statement is used by the code to print each element of the array to the output within the inner loop, followed by a space character. This actually prints the matrix's elements one after the other, separated by spaces.

The code uses the echo statement to print a line break (<BR>) to advance to the next line in the output after the inner loop has finished for each row. This results in a formatted output that presents the matrix's components as a grid with each row on its own line.

PHP Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!