php - How can I access an array/object?
I have the following array and when I doprint_r(array_values($get_user));
, I get:
Array (
[0] => 10499478683521864
[1] => 07/22/1983
[2] => [email protected]
[3] => Alan [4] => male
[5] => Malmsteen
[6] => https://www.facebook.com app_scoped_user_id/1049213468352864/
[7] => stdClass Object (
[id] => 102173722491792
[name] => Jakarta, Indonesia
)
[8] => id_ID
[9] => El-nino
[10] => Alan El-nino Malmsteen
[11] => 7
[12] => 2015-05-28T04:09:50+0000
[13] => 1
)
I tried to access the array as followed:
echo $get_user[0];
But this displays me:
undefined 0
Note:
I get this array from the Facebook SDK 4, so I don't know the original array structure.
How can I access as an example the value[email protected]
from the array?
Answer
Solution:
From the question we can't see the structure of input array. It maybe
array ('id' => 10499478683521864, 'date' => '07/22/1983')
. So when you ask $demo[0] you use undefind index.Array_values lost keys and return array with numerous keys making array as
array(10499478683521864, '07/22/1983'...)
. This result we see in the question.So, you can take an array item values by the same way
Answer
Solution:
If your output from
print_r($var)
is e.g:then do
$var['demo'][0]
If the output from
print_r($var)
is e.g:then do
$var[0]
Answer
Solution:
Before calling
array_values()
on the response data, I am going to assume that your data was associative and it looks a little like this:There is no benefit in re-indexing the keys of the payload. If your intention was to cast the data as an array, that is accomplished by decoding the json string with
json_decode($response, true)
, otherwisejson_decode($response)
.If you try to pass
$response
as an object intoarray_values()
, from PHP8 you will generateFatal error: Uncaught TypeError: array_values(): Argument #1 ($array) must be of type array, stdClass given
.In the above supplied data structure, there is an array with associative keys.
$response['id']
to access10499478683521864
$response['gender']
to accessmale
$response['location']
to access(object) ['id' => 102173722491792, 'name' => 'Jakarta, Indonesia']
location
(second level), "arrow syntax" is required because the data is an object.$response['location']->id
to access102173722491792
$response['location']->name
to accessJakarta, Indonesia
After calling
array_values()
on your response, the structure is an indexed array, so use square braces with unquoted integers.$response[0]
to access10499478683521864
$response[4]
to accessmale
$response[7]
to access(object) ['id' => 102173722491792, 'name' => 'Jakarta, Indonesia']
$response[7]->id
to access102173722491792
$response[7]->name
to accessJakarta, Indonesia
When you aren't sure what data type you are working with, use
.
For cases when an object property (key) has illegal characters or there is immediately trailing characters that conflict with the key (see: 1, 2, 3), wrap the key in quotes and curly braces (or only curly braces for integers) to prevent syntax breakage.
If you want to loop through all of the elements in an array or object, a
foreach()
is suitable for both.Code: (Demo)
Output:
Answer
Solution:
I wrote a small function for accessing properties in either arrays or objects. I use it quite a bit find it pretty handy
Answer
Solution:
//you can call this function whenever you want to access item from the array or object. this function prints that respective value from the array/object as per key.
Answer
Solution:
From the question we can't see the structure of input array. It maybe
array ('id' => 10499478683521864, 'date' => '07/22/1983')
. So when you ask $demo[0] you use undefind index.Array_values lost keys and return array with numerous keys making array as
array(10499478683521864, '07/22/1983'...)
. This result we see in the question.So, you can take an array item values by the same way
Answer
Solution:
If your output from
print_r($var)
is e.g:then do
$var['demo'][0]
If the output from
print_r($var)
is e.g:then do
$var[0]
Answer
Solution:
Before calling
array_values()
on the response data, I am going to assume that your data was associative and it looks a little like this:There is no benefit in re-indexing the keys of the payload. If your intention was to cast the data as an array, that is accomplished by decoding the json string with
json_decode($response, true)
, otherwisejson_decode($response)
.If you try to pass
$response
as an object intoarray_values()
, from PHP8 you will generateFatal error: Uncaught TypeError: array_values(): Argument #1 ($array) must be of type array, stdClass given
.In the above supplied data structure, there is an array with associative keys.
$response['id']
to access10499478683521864
$response['gender']
to accessmale
$response['location']
to access(object) ['id' => 102173722491792, 'name' => 'Jakarta, Indonesia']
location
(second level), "arrow syntax" is required because the data is an object.$response['location']->id
to access102173722491792
$response['location']->name
to accessJakarta, Indonesia
After calling
array_values()
on your response, the structure is an indexed array, so use square braces with unquoted integers.$response[0]
to access10499478683521864
$response[4]
to accessmale
$response[7]
to access(object) ['id' => 102173722491792, 'name' => 'Jakarta, Indonesia']
$response[7]->id
to access102173722491792
$response[7]->name
to accessJakarta, Indonesia
When you aren't sure what data type you are working with, use
.
For cases when an object property (key) has illegal characters or there is immediately trailing characters that conflict with the key (see: 1, 2, 3), wrap the key in quotes and curly braces (or only curly braces for integers) to prevent syntax breakage.
If you want to loop through all of the elements in an array or object, a
foreach()
is suitable for both.Code: (Demo)
Output:
Answer
Solution:
I wrote a small function for accessing properties in either arrays or objects. I use it quite a bit find it pretty handy
Answer
Solution:
//you can call this function whenever you want to access item from the array or object. this function prints that respective value from the array/object as per key.
Answer
Solution:
To access an
{-code-{-code-32}}
or{-code-2}
you how to use two different operators.To access {-code-{-code-32}} elements you have to use
[]
.On older PHP versions, an alternative syntax using
{}
was also allowed:Difference between declaring an {-code-{-code-32}} and accessing an {-code-{-code-32}} element
Defining an {-code-{-code-32}} and accessing an {-code-{-code-32}} element are two different things. So don't mix them up.
To define an {-code-{-code-32}} you can use
{-code-{-code-32}}()
or for PHP >=5.4[]
and you assign/set an {-code-{-code-32}}/-element. While when you are accessing an {-code-{-code-32}} element with[]
as mentioned above, you get the value of an {-code-{-code-32}} element opposed to setting an element.Access {-code-{-code-32}} element
To access a particular element in an {-code-{-code-32}} you can use any expression inside
[]
or{}
which then evaluates to the key you want to access:So just be aware of what expression you use as key and how it gets interpreted by PHP:
Access multidimensional {-code-{-code-32}}
If you have multiple {-code-{-code-32}}s in each other you simply have a multidimensional {-code-{-code-32}}. To access an {-code-{-code-32}} element in a sub {-code-{-code-32}} you just have to use multiple
[]
.To access an {-code-2} property you have to use
{-code-{-code-32}5}
.If you have an {-code-2} in another {-code-2} you just have to use multiple
{-code-{-code-32}5}
to get to your {-code-2} property.Note:
Also you have to be careful if you have a property name which is invalid! So to see all problems, which you can face with an invalid property name see this question/answer. And especially this one if you have numbers at the start of the property name.
You can only access properties with public visibility from outside of the class. Otherwise (private or protected) you need a method or reflection, which you can use to get the value of the property.
Now if you have {-code-{-code-32}}s and {-code-2}s mixed in each other you just have to look if you now access an {-code-{-code-32}} element or an {-code-2} property and use the corresponding operator for it.
I hope this gives you a rough idea how you can access {-code-{-code-32}}s and {-code-2}s, when they are nested in each other.
Note:
If it is called an {-code-{-code-32}} or {-code-2} depends on the outermost part of your variable. So
{-code-{-code-32}9}
is an {-code-{-code-32}} even if it has (nested) {-code-2}s inside of it and${-code-2}{-code-{-code-32}5}property = {-code-{-code-32}}();
is an {-code-2} even if it has (nested) {-code-{-code-32}}s inside.And if you are not sure if you have an {-code-2} or {-code-{-code-32}}, just use
.
Don't get yourself confused if someone uses another coding style than you:
Arrays, Objects and Loops
If you don't just want to access a single element you can loop over your nested {-code-{-code-32}} / {-code-2} and go through the values of a particular dimension.
For this you just have to access the dimension over which you want to loop and then you can loop over all values of that dimension.
As an example we take an {-code-{-code-32}}, but it could also be an {-code-2}:
If you loop over the first dimension you will get all values from the first dimension:
Means here in the first dimension you would only have {-code-32} element with the key(
{-code-25}
){-code-26}
and the value({-code-27}
):If you loop over the second dimension you will get all values from the second dimension:
Means here in the second dimension you would have 3 element with the keys(
{-code-25}
){-code-3{-code-32}}
,{-code-32}
,2
and the values({-code-27}
):And with this you can loop through any dimension which you want no matter if it is an {-code-{-code-32}} or {-code-2}.
Analyse
/
/
output
All of these 3 debug functions output the same {-code-26}, just in another format or with some meta {-code-26} (e.g. type, size). So here I want to show how you have to read the output of these functions to know/get to the way how to access certain {-code-26} from your {-code-{-code-32}}/{-code-2}.
Input {-code-{-code-32}}:
var_dump()
output:print_r()
output:var_export()
output:So as you can see all outputs are pretty similar. And if you now want to access the value 2 you can just start from the value itself, which you want to access and work your way out to the "top left".
{-code-32}. We first see, that the value 2 is in an {-code-{-code-32}} with the key {-code-32}
This means we have to use
[]
to access the value 2 with[{-code-32}]
, since the value has the key/index {-code-32}.2. Next we see, that the {-code-{-code-32}} is assigned to a property with the name property of an {-code-2}
This means we have to use
{-code-{-code-32}5}
to access the property of the {-code-2}, e.g.{-code-{-code-32}5}property
.So until now, we know that we have to use
{-code-{-code-32}5}property[{-code-32}]
.3. And at the end we see, that the outermost is an {-code-{-code-32}}
As we know that we have to access an {-code-{-code-32}} element with
[]
, we see here that we have to use["key"]
to access the {-code-2}. We now can put all these parts together and write:And the output will be:
There are a few things, which you have to know, so that you don't spend hours on it finding them.
"Hidden" characters
Sometimes you have characters in your keys, which you don't see on the first look in the browser. And then you're asking yourself, why you can't access the element. These characters can be: tabs (
\t
), new lines (\n
), spaces or html tags (e.g.</p>
,<b>
), etc.As an example if you look at the output of
print_r()
and you see:Then you are trying to access the element with:
But you are getting the notice:
This is a good indication that there must be some hidden characters, since you can't access the element, even if the keys seems pretty correct.
The trick here is to use
var_dump()
+ look into your source code! (Alternative:highlight_string(print_r($variable, TRUE));
)And all of the sudden you will maybe see stuff like this:
Now you will see, that your key has a html tag in it + a new line character, which you didn't saw in the first place, since
print_r()
and the browser didn't showed that.So now if you try to do:
You will get your desired output:
Never trust the output of
print_r()
orvar_dump()
if you look at XMLYou might have an XML file or string loaded into an {-code-2}, e.g.
Now if you use
var_dump()
orprint_r()
you will see:So as you can see you don't see the attributes of title. So as I said never trust the output of
var_dump()
orprint_r()
when you have an XML {-code-2}. Always useto see the full XML file/string.
So just use one of the methods shown below:
And then you will get the output:
For more information see:
General (symbols, errors)
Property name problems
Answer
Solution:
From the question we can't see the structure of input array. It maybe
array ('id' => 10499478683521864, 'date' => '07/22/1983')
. So when you ask $demo[0] you use undefind index.Array_values lost keys and return array with numerous keys making array as
array(10499478683521864, '07/22/1983'...)
. This result we see in the question.So, you can take an array item values by the same way
Answer
Solution:
If your output from
print_r($var)
is e.g:then do
$var['demo'][0]
If the output from
print_r($var)
is e.g:then do
$var[0]
Answer
Solution:
Before calling
array_values()
on the response data, I am going to assume that your data was associative and it looks a little like this:There is no benefit in re-indexing the keys of the payload. If your intention was to cast the data as an array, that is accomplished by decoding the json string with
json_decode($response, true)
, otherwisejson_decode($response)
.If you try to pass
$response
as an object intoarray_values()
, from PHP8 you will generateFatal error: Uncaught TypeError: array_values(): Argument #1 ($array) must be of type array, stdClass given
.In the above supplied data structure, there is an array with associative keys.
$response['id']
to access10499478683521864
$response['gender']
to accessmale
$response['location']
to access(object) ['id' => 102173722491792, 'name' => 'Jakarta, Indonesia']
location
(second level), "arrow syntax" is required because the data is an object.$response['location']->id
to access102173722491792
$response['location']->name
to accessJakarta, Indonesia
After calling
array_values()
on your response, the structure is an indexed array, so use square braces with unquoted integers.$response[0]
to access10499478683521864
$response[4]
to accessmale
$response[7]
to access(object) ['id' => 102173722491792, 'name' => 'Jakarta, Indonesia']
$response[7]->id
to access102173722491792
$response[7]->name
to accessJakarta, Indonesia
When you aren't sure what data type you are working with, use
.
For cases when an object property (key) has illegal characters or there is immediately trailing characters that conflict with the key (see: 1, 2, 3), wrap the key in quotes and curly braces (or only curly braces for integers) to prevent syntax breakage.
If you want to loop through all of the elements in an array or object, a
foreach()
is suitable for both.Code: (Demo)
Output:
Answer
Solution:
I wrote a small function for accessing properties in either arrays or objects. I use it quite a bit find it pretty handy
Answer
Solution:
//you can call this function whenever you want to access item from the array or object. this function prints that respective value from the array/object as per key.