PHP how to make a two -dimensional array

Create a two-dimensional array in PHP using a simple example to learn the basics of the language.

Creating a two-dimensional array in PHP

A two-dimensional array in PHP is a type of array that contains multiple arrays inside of it. It can be used to store data in a structured way and allows you to access elements quickly. A two-dimensional array is also known as a matrix.

The syntax for creating a two-dimensional array in PHP is as follows:

$array_name = array(
	array(value1, value2, …),
	array(value1, value2, …),

Where $array_name is the name of the array, and the inner arrays are the elements of the two-dimensional array.

For example, if we wanted to create an array to store the names of three people, we could create a two-dimensional array like this:

$people = array(
	array("John", "Smith"),
	array("Jane", "Doe"),
	array("Bob", "Jones")

We can access elements in the array using two indices, one for the inner array and one for the element in the inner array. For example, if we wanted to access the first name of the second person, we would use the following code:

echo $people[1][0]; // Outputs "Jane"

We can also use looping constructs such as foreach to iterate over the elements of a two-dimensional array:

foreach($people as $person) {
	echo $person[0] . " " . $person[1] . "<br>";

// Outputs:
// John Smith 
// Jane Doe 
// Bob Jones

Two-dimensional arrays are useful when you need to store and access data in a structured way. They are also easy to create and manipulate using the built-in functions in PHP.

Answers (0)