1

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?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
user3452136
  • 125
  • 1
  • 1
  • 11
  • 1
    You shouldn't, just use the array whenever you need any of its values. – jeroen Feb 02 '17 at 15:30
  • I'm having a problem with that. For example, `echo $myArray[0]['name'];` doesn't output what I'd expect. – user3452136 Feb 02 '17 at 15:38
  • What does it output? When I tried it it output "Paul". And @jeroen is right, you'll just clutter up the variable space if you start trying to convert an array into variables. – GordonM Feb 02 '17 at 16:29
  • I think the problem is that what I'm trying to do is convert an entire string into an array. I'll probably have to split up the string via "explode" or "preg_split". – user3452136 Feb 02 '17 at 16:58

1 Answers1

3

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.

Vikash
  • 3,391
  • 2
  • 23
  • 39