user3452136
user3452136

Reputation: 125

How to access nested associative array data in PHP

I have an indexed array that contains a nested associative array AND a nested indexed array:

$myArray = array ( 
    0 => array (
        'name' => 'Paul', 
        'age' => '23', 
        'hobbies' => array ( 
            0 => 'basketball',
        ), 
        'pets' => 'dog',
    ),
);

How can I access all of these values and convert them into variables?

Upvotes: 1

Views: 2044

Answers (1)

Vikash
Vikash

Reputation: 3561

You can just access from Array

Write your array like this

$myArray = [
  0 => [
      'name' => 'Paul',
      'age' => '23',
      'hobbies' => [
              0 => 'basketball',
            ],
      'pets' => 'dog'
    ]
];

Suppose you want to access name of first elements

echo $myArray[0]['name']; // it will print 'Paul'
echo $myArray[0]['hobbies'][0]; // it will print basketball

Now you can fetch like above.

Upvotes: 3

Related Questions