How to make an invested PHP array

PHP: Learn how to create a multidimensional array with an example. Create, access & modify nested arrays & get more out of your code!

Creating an Invested PHP Array

An invested PHP array is an array with multiple levels of nested elements. It's a useful tool for creating complex data structures in PHP. Here's an example of how to make an invested array:

$data = array(
    'person' => array(
        'name' => 'John Doe',
        'age' => 35,
        'address' => array(
            'street' => '123 Main Street',
            'city' => 'San Francisco',
            'state' => 'CA'
        )
    ),
    'pet' => array(
        'type' => 'dog',
        'name' => 'Spot'
    )
);
In this example, we create an array called $data. Inside this array, we have two nested elements: a person element, and a pet element. The person element contains three elements itself: name, age, and address. The address element contains three more elements: street, city, and state. Finally, the pet element contains two elements: type and name. These nested elements allow us to store a lot of data in a single array. We can access any element by using the [] syntax:

echo $data['person']['name'];  // Outputs 'John Doe'
echo $data['person']['address']['city'];  // Outputs 'San Francisco'
echo $data['pet']['name'];  // Outputs 'Spot'
We can also add elements to an invested array by using the [] syntax in an assignment statement:

$data['person']['favorite_color'] = 'blue';
This statement adds a new element, favorite_color, to the person element. Now we can access this element like this:

echo $data['person']['favorite_color'];  // Outputs 'blue'
As you can see, an invested array is a powerful tool for creating complex data structures in PHP.

Answers (0)