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?

4
  • 1
    You shouldn't, just use the array whenever you need any of its values. Commented Feb 2, 2017 at 15:30
  • I'm having a problem with that. For example, echo $myArray[0]['name']; doesn't output what I'd expect. Commented Feb 2, 2017 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. Commented Feb 2, 2017 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". Commented Feb 2, 2017 at 16:58

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

When I do that, I just get the letter 'a', which I'm assuming is from the word 'array'.
You can copy & paste my code here. phpfiddle.org . Run it. I have just checked its working correctly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.