PHP Arrays (With Advanced Program Examples)

What are PHP arrays?

Arrays in PHP are a type of data structure that allows us to store multiple elements of similar data type under a single variable thereby saving us the effort of creating a different variable for every data.

The arrays are helpful in creating a list of elements of similar types, which can be accessed using their index or key.

What are the different types of arrays in PHP?

There are three types of arrays, and each array value is accessed using an identifier known as the array index.

  • Numeric array − A collection with a number index. The storage and access of values are linear.
  • Associative array − A string-based array index. This stores element values in conjunction with their respective key values, as opposed to in strict linear index order.
  • Multi-dimensional array − The values of an array comprising one or more arrays are accessed using multiple indices.

1. Numeric Arrays

These arrays are capable of storing numbers, strings, and any object, but their indexes are represented by integers. By default, the array index starts at zero.

Example:

The following example demonstrates how to construct and access arrays of numbers.

Here, we have created an array using the array() function. The function reference explains this function.

<?php
// First Method to make a numeric array
$numbers = array( 1, 2, 3, 4, 5);

   echo "First Method: The number arrays are $numbers[0], $numbers[1], $numbers[2], $numbers[3], and $numbers[4].\n";

echo "\n";

// Second Method to make a numeric array
$numbers[0] = "One";
$numbers[1] = "Two";
$numbers[2] = "Three";
$numbers[3] = "Four";
$numbers[4] = "Five";

foreach( $numbers as $value ) {
   echo "Second Method: $value \n";
}
?>

Output:

First Method: The number arrays are 1, 2, 3, 4, and 5.

Second Method: One 
Second Method: Two 
Second Method: Three 
Second Method: Four 
Second Method: Five 

Traversing: Using PHP loops, we may traverse an indexed array. The indexed array can be accessed in two ways. First, use a for loop, followed by a foreach loop.

Example:

<?php
 
// Creating an array called $name_list
$name_list = array("Prince", "Glenn", "Paul", "Jude", "Adones");
 
// first method is foreach loop
echo "Using foreach loop:\n";
foreach ($name_list as $val){
    echo "-".$val."\n";
}
 
// count function is used to count the number of index inside the array
$count_names = count($name_list);
echo "\nArray name_list has $count_names elements\n";

// second method is for loop
echo "Using for loop: \n";
$i = 0;
for($i; $i < $count_names; $i++){
    echo "-".$name_list[$i]."\n";
}
 
?>

Output:

Using foreach loop:
-Prince
-Glenn
-Paul
-Jude
-Adones

Array name_list has 5 elements
Using for loop: 
-Prince
-Glenn
-Paul
-Jude
-Adones

Associative Arrays

In terms of functionality, associative arrays are quite similar to numeric arrays, but their indexes are distinct. So that a strong link can be made between keys and values, the index of an associative array will be a string. 

Employee salary would not be best stored in a numerically indexed array. Instead, we could use the employees’ names as the “keys” and their salaries as the “values” in our associative array.

Example:

<?php
   // First Method on making associative array
   $salary = array("Prince" => 10000, "Grace" => 12000, "Paul" => 15000);
   
   echo "First Method:\n";
   echo "Prince's Salary: ". $salary['Prince'] . "\n";
   echo "Grace's Salary: ".  $salary['Grace']. "\n";
   echo "Paul's Salary: ".  $salary['Paul']. "\n";
   
   echo "\n";
   
   // Second Method on making associative array
   $salary['Prince'] = "low";
   $salary['Grace'] = "medium";
   $salary['Paul'] = "high";
   
   echo "Second Method:\n";
   echo "Prince's Salary: ". $salary['Prince'] . "\n";
   echo "Grace's Salary: ".  $salary['Grace']. "\n";
   echo "Paul's Salary: ".  $salary['Paul']. "\n";
?>

Output:

First Method:
Prince's Salary: 10000
Grace's Salary: 12000
Paul's Salary: 15000

Second Method:
Prince's Salary: low
Grace's Salary: medium
Paul's Salary: high

Traversing Associative Arrays: Loops can be used to move through associative arrays in the same way they can be used to move through numeric arrays.

There are two ways to loop through the associative array. First, with the for loop, and then with the foreach.

Example:

<?php
 
// Creating an associative array
$married = array(
  "Prince"=>"Grace",
  "Jude"=>"Kristel",
  "Adones"=>"Myrell",
  "Ted"=>"Gladys",
  "Joken"=>"Charlotte"
  );
 
// Using the foreach loop in printing array
echo "Using foreach loop: \n";
foreach ($married as $val => $val_value){
    echo "".$val." and ".$val_value." are married\n";
}
 
// Using the for loop in printing array
echo "\nUsing for loop: \n";
$keys = array_keys($married);
$round = count($married);
 
for($i=0; $i < $round; ++$i) {
    echo $keys[$i] . ' & ' . $married[$keys[$i]] . "\n";
}
 
?>

Output:

Using foreach loop: 
Prince and Grace are married
Jude and Kristel are married
Adones and Myrell are married
Ted and Gladys are married
Joken and Charlotte are married

Using for loop: 
Prince & Grace
Jude & Kristel
Adones & Myrell
Ted & Gladys
Joken & Charlotte

Multi-dimensional Arrays

In a multi-dimensional array, each element of the main array can also be an array. Each of the sub-elements arrays can be another array, and so on.

To get to the values in a multidimensional array, you need to use more than one index.

Example:

In this example, we make a two-dimensional array to store the grades of three students in three subjects.

This is an example of an associative array. In the same way, you can also make a numeric array.

<?php
$marks = array(
	"Prince" => array (
    "SANDES" => 1.3,
    "SYSPRO" => 1.4,	
    "WEBDEV" => 1.2
   ),
	"Grace" => array (
    "SANDES" => 1.5,
    "SYSPRO" => 1.7,	
    "WEBDEV" => 2.0
   ),
	"Nym" => array (
    "SANDES" => 3,
    "SYSPRO" => 2.7,	
    "WEBDEV" => 2.8
   )
);

   // Accessing the multi-dimensional array
   echo "Prince's Grades in Web Development: " ;
   echo $marks['Prince']['WEBDEV'] . "\n"; 
   
   echo "Grace's Grades in System and Design: " ;
   echo $marks['Grace']['SANDES'] . "\n"; 
   
   echo "Nym's Grades in System Programming: " ;
   echo $marks['Nym']['SYSPRO'] . "\n"; 
?>

Output:

Prince's Grades in Web Development: 1.2
Grace's Grades in System and Design: 1.5
Nym's Grades in System Programming: 2.7

Traversing Multidimensional Arrays: We can use nested for and foreach loops to move through a multidimensional array.

That is one for the outer array’s loop and another for the inner array’s loop.

Example:

<?php
$contacts = array(
	"Prince" => array (
		"Mobile" => "09124056874",
		"Email" => "[email protected]"
		),
	"Grace" => array (
		"Mobile" => "09587451254",
		"Email" => "[email protected]"
		),
	"Nym" => array (
		"Mobile" => "09562368745",
		"Email" => "[email protected]"
	)
);

$keys = array_keys($contacts);
$i = 0;

for($i; $i < count($contacts); $i++) {
    echo $keys[$i] . "\n";
    foreach($contacts[$keys[$i]] as $key => $value) {
        echo $key . ": " . $value . "\n";
    }
    echo "\n";
}
?>

Output:

Prince
Mobile: 09124056874
Email: [email protected]

Grace
Mobile: 09587451254
Email: [email protected]

Nym
Mobile: 09562368745
Email: [email protected]

PHP array of objects

In PHP, we can make an array of objects with the help of the array() function. The object will be passed to the function as an argument, and the function will make an array of those objects.

We can make objects by making a class and giving that class some properties. Some values will be given to the class’s properties. Lastly, the properties and their values will be put into the array as a key-value pair.

For example, we will make a class called BookStore, and then we will make two public properties called $title and $year. Then, we will use the new keyword to make an object of the BookStore class called $book1.

Fill in the object’s properties with any values you think are right. In the same way, make another object called $book2 and give its properties any values that work.

Next, make a variable called $books and give it a array() function that takes two objects as input. Lastly, use the print_r() function to show the books in the array $books.

Example:

<?php
class BookStore
{
	public $title;
	public $year;
}

$book1 = new BookStore();
	$book1->title = 'The secret life of Walter Mitty';
	$book1->year = '2013';
  
$book2 = new BookStore();
	$book2->title = 'The Chronicles of Narnia';
	$book2->year = '1950';
  
$books = array($book1, $book2);
?>
<pre><?php print_r($books);?> </pre>

In the example above, we have made a group of BookStore objects by putting them in a list. We can determine the indices 0 and 1 for each BookStore object.

As stated above, the properties and values of each object are made up of a key-value pair.

Output:

<pre>Array
(
    [0] => BookStore Object
        (
            [title] => The secret life of Walter Mitty
            [year] => 2013
        )

    [1] => BookStore Object
        (
            [title] => The Chronicles of Narnia
            [year] => 1950
        )

)
 </pre>

Array of stdClass Objects in PHP

By making an object called stdClass in PHP, we can make an array of objects. This stdClass is part of the set of functions that come with PHP.

It is not an object’s base class. Instead, it is an empty class that can be used to set dynamic properties and typecast.

We can make a stdClass object, which by definition is an array. Then, we can use the indexes to give the object its dynamic properties.

For example, you could make an object out of the $books[] array by using the new keyword. Then, set the index of the $books[] array to 0 and assign the properties title and year.

Give the properties the values you want, then do the same thing for the index 1 in the $books[] array. The $books array will be printed next.

Example:

<?php
  $books[] = new stdClass;
  
  $books[0]->title = 'The Secret Life of Walter Mitty';
  $books[0]->year = '2013';
  
  $books[1]->title = 'The Chronicles of Narnia';
  $books[1]->year = '1950';
?>
<pre>
  <?php
    print_r($books);
  ?>
</pre>

In the output section, you can see that the code above makes an array of stdClass objects.

Output:

<pre>
  Array
(
    [0] => stdClass Object
        (
            [title] => The Secret Life of Walter Mitty
            [year] => 2013
        )

    [1] => stdClass Object
        (
            [title] => The Chronicles of Narnia
            [year] => 1950
        )

)
</pre>

More About Array

Summary

In summary, we have covered what arrays are in PHP as well as the different types of arrays: numerical arrays, associative arrays, and multi-dimensional arrays, and we have provided some examples of each.

Lastly, if you want to learn more about PHP Arrays, please leave a comment below. We’ll be happy to hear it!

Leave a Comment