Home PHP PHP: Nested Arrays

Looping Through Nested PHP Arrays

By a TechBitBytes Contributor, September 21, 2023
6 MIN READ |

If you are not familiar with PHP arrays, more so on creating, accessing, and modifying PHP arrays, we recommend that you first read A Beginner's Guide to Indexed and Associative Arrays. We also recommend you read on looping Multidimensional Arrays. The tutorial is designed for PHP beginners who want to learn the basics of nesting in PHP array().

A Simple Array()

<?php

	$users = array('Jane', 'Mark', 'Susan', 'Peter');	//creates an array
	
	echo $users[1];
	
	/*
	Outputs Mark
	*/
?>

The example above shows how to create a simple array $users with 4 elements. Why does Line 5 output Mark and not Jane? Remember that, by default, Indexed arrays begin from 0 and not 1. Therefore, the value Jane can be accessed by $users[0] and the value Mark by $users[1].

Now, assume you want to add more personal information of the users and store it in arrays. The most obvious way would be to create a simple arrays for each of the information group, matching the index of each group to the user in the $users as demonstrated below.

<?php

	$users = array('Jane', 'Mark', 'Susan', 'Peter');	//creates an array
	$age = array(23, 32, 34, 29); //holds user's age
	$favourite_color = array('Red', 'Blue', 'Green', 'Black'); //holds user's favourite color
	

	echo $users[1] . 'is ' . $age[1] . ' years old and loves the color ' . $favourite_color[1];
	
	/*
	Outputs Mark is 32 years old and loves the color Blue
	*/
?>

Although the above method is the most obvious, it is not the most suitable and is prone to errors, both logic and syntax errors. For instance, you must match each value in each of the array to be logically correct. Assume you wanted to change Susan's age. You must find the exact value of Susan in $age array.

In the example above, it is easy. Now. Imagine a $users array with 100 names and you need to change the value of $users[67] in the corresponding $age array. That will be problematic.

That is where nested arrays come in handy.

What are Nested Arrays?

Nesting, in the concept of arrays can be simplify described as having an Array inside another array. The inner arrays are under the scope of outer array, which means that we can access these inner array elements based on outer array name.

Nesting uses the concept of multidimensional arrays. Basically, multidimensional arrays are arrays that hold other arrays.

You can nest both indexed and associative arrays.

1. Nesting Indexed Arrays

<?php

	$users = array(
				array('Jane', 23, 'Red'),
				array('Mark', 32, 'Blue'),
				array('Susan', 34, 'Green'),
				array('Peter', 29, 'Black')
			);

	echo $users[0][0] . ' is ' . $users[0][1] . ' years old and loves the color ' . $users[0][2];
	
	/*
	Outputs Jane is 23 years old and loves the color Red
	*/
?>

2. Nesting Associative Arrays

<?php

	$users = array(
				'person_1' => array('Jane', 23, 'Programming'),
				'person_2' => array('Mark', 32, 'Watching Music'),
				'person_3'=> array('Susan', 34, 'Skating'),
				'person_4'=> array('Peter', 29, 'Reading')
			);

	echo $users['person_1'][0] . ' is ' . $users['person_1'][1] . ' years old and loves the color ' . $users['person_1'][2];
	
	/*
	Outputs Jane is 23 years old and loves the color Programming
	*/
?>

Using nested arrays allows you to group arrays. This makes it easier to add new arrays to the group, and change the values of an array.

How to Loop through Nested Arrays

You can loop through nested arrays through the for and the foreach loops.

Below, we have an example of a loop using foreach since the array is associative and not indexed:

<?php
	$users = array(
		'person_1' => array('Jane', 23, 'Programming'),
		'person_2' => array('Mark', 32, 'Watching Music'),
		'person_3'=> array('Susan', 34, 'Skating'),
		'person_4'=> array('Peter', 29, 'Reading')
	);

	foreach($users as $prsn=>$user_traits){
		$user_details = $user_traits; //an array object
		echo $user_details[0] . ' loves ' . $user_details[2] . '
'; } ?>

	Jane loves Programming
	Mark loves Watching Music
	Susan loves Skating
	Peter loves Reading

You can also nest loops to help loop through nested arrays. This involves using the foreach loop within the for loop, or vise-versa to access the individual array containing the keys and elements as demonstrated in the example below..

<?php
	
	$users = array(
				array('Jane'=>'PHP'),
				array('Mark'=>'JavaScript'),
				array('Susan'=>'Python'),
				array('Peter'=>'Java')
			);
			
	for($i=0; $i < count($users); $i++){
		$sec_array = $users[$i]; //store individual arrays within the $users array
		foreach($sec_array as $prsn=>$value){
			echo $prsn . '\'s favorite programming language is ' . $value . '<br>';
		}
	}
?>

	Jane's favorite programming language is PHP
	Mark's favorite programming language is JavaScript
	Susan's favorite programming language is Python
	Peter's favorite programming language is Java

 

  This article is written to the best of the author's knowledge. TechBitBytes(TBB) ensures that all articles are constantly updated with the latest information.