1

Im return an array from a function and I want to grabe the elements in the array and store them as varibles.

When I do a:

$array = fetchArray();
var_dump ($array);

I get this:

array(size = 1)
0 =>
    array(size = 1)
0 =>
    array(size = 7)
'customerid' => string '31' (length = 2)
'username' => string 'test' (length = 4)
'active' => string '1' (length = 1)
'CustomerName' => string 'Tobias Axbard' (length = 13)
'email' => string '[email protected]' (length = 25)
'phonenumber' => string '0738032207' (length = 10)
'isstaff' => string '0' (length = 1)

So than I would like to do something like this:

$username = $array["username"];
echo $username;

But insted of the string "test" from the array I get an error:

Notice: Undefined index: username 

Any ides?

1
  • 1
    You can use the PHP array function extract. I answered a question here which might help you. Commented Sep 11, 2021 at 15:32

2 Answers 2

2

Note that $array has two nested arrays inside it which you need to access:

$username = $array[0][0]["username"];
Sign up to request clarification or add additional context in comments.

Comments

2

Well, youre array is nested, so an array in an array in an array.

Most outer array is $array. The first element of $array, $array[0], is an other array, and that one contains again another one as first element $array[0][0] which contains the data you want to access.

So you'll have to use $array[0][0]['username'] to access the values.

Use $array = $array[0][0] to 'move it up', or even use extract($array[0][0]) to immediatly convert the array keys to variables: https://www.php.net/manual/en/function.extract.php

Comments

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.