Unable to access a property of stdClass object [duplicate] - php

I have the following array and when I do print_r(array_values($get_user));, I get:
Array (
[0] => 10499478683521864
[1] => 07/22/1983
[2] => email#saya.com
[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#saya.com from the array?

To access an array or object you how to use two different operators.
Arrays
To access array elements you have to use [].
echo $array[0];
On older PHP versions, an alternative syntax using {} was also allowed:
echo $array{0};
Difference between declaring an array and accessing an array element
Defining an array and accessing an array element are two different things. So don't mix them up.
To define an array you can use array() or for PHP >=5.4 [] and you assign/set an array/-element. While when you are accessing an array element with [] as mentioned above, you get the value of an array element opposed to setting an element.
//Declaring an array
$arrayA = array ( /*Some stuff in here*/ );
$arrayB = [ /*Some stuff in here*/ ]; //Only for PHP >=5.4
//Accessing an array element
echo $array[0];
Access array element
To access a particular element in an array you can use any expression inside [] or {} which then evaluates to the key you want to access:
$array[(Any expression)]
So just be aware of what expression you use as key and how it gets interpreted by PHP:
echo $array[0]; //The key is an integer; It accesses the 0's element
echo $array["0"]; //The key is a string; It accesses the 0's element
echo $array["string"]; //The key is a string; It accesses the element with the key 'string'
echo $array[CONSTANT]; //The key is a constant and it gets replaced with the corresponding value
echo $array[cOnStAnT]; //The key is also a constant and not a string
echo $array[$anyVariable] //The key is a variable and it gets replaced with the value which is in '$anyVariable'
echo $array[functionXY()]; //The key will be the return value of the function
Access multidimensional array
If you have multiple arrays in each other you simply have a multidimensional array. To access an array element in a sub array you just have to use multiple [].
echo $array["firstSubArray"]["SecondSubArray"]["ElementFromTheSecondSubArray"]
// ├─────────────┘ ├──────────────┘ ├────────────────────────────┘
// │ │ └── 3rd Array dimension;
// │ └──────────────────── 2d Array dimension;
// └───────────────────────────────────── 1st Array dimension;
Objects
To access an object property you have to use ->.
echo $object->property;
If you have an object in another object you just have to use multiple -> to get to your object property.
echo $objectA->objectB->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.
Arrays & Objects
Now if you have arrays and objects mixed in each other you just have to look if you now access an array element or an object property and use the corresponding operator for it.
//Object
echo $object->anotherObject->propertyArray["elementOneWithAnObject"]->property;
//├────┘ ├───────────┘ ├───────────┘ ├──────────────────────┘ ├──────┘
//│ │ │ │ └── property ;
//│ │ │ └───────────────────────────── array element (object) ; Use -> To access the property 'property'
//│ │ └─────────────────────────────────────────── array (property) ; Use [] To access the array element 'elementOneWithAnObject'
//│ └────────────────────────────────────────────────────────── property (object) ; Use -> To access the property 'propertyArray'
//└────────────────────────────────────────────────────────────────── object ; Use -> To access the property 'anotherObject'
//Array
echo $array["arrayElement"]["anotherElement"]->object->property["element"];
//├───┘ ├────────────┘ ├──────────────┘ ├────┘ ├──────┘ ├───────┘
//│ │ │ │ │ └── array element ;
//│ │ │ │ └─────────── property (array) ; Use [] To access the array element 'element'
//│ │ │ └─────────────────── property (object) ; Use -> To access the property 'property'
//│ │ └────────────────────────────────────── array element (object) ; Use -> To access the property 'object'
//│ └────────────────────────────────────────────────────── array element (array) ; Use [] To access the array element 'anotherElement'
//└──────────────────────────────────────────────────────────── array ; Use [] To access the array element 'arrayElement'
I hope this gives you a rough idea how you can access arrays and objects, when they are nested in each other.
Note:
If it is called an array or object depends on the outermost part of your variable. So [new StdClass] is an array even if it has (nested) objects inside of it and $object->property = array(); is an object even if it has (nested) arrays inside.
And if you are not sure if you have an object or array, just use gettype().
Don't get yourself confused if someone uses another coding style than you:
//Both methods/styles work and access the same data
echo $object->anotherObject->propertyArray["elementOneWithAnObject"]->property;
echo $object->
anotherObject
->propertyArray
["elementOneWithAnObject"]->
property;
//Both methods/styles work and access the same data
echo $array["arrayElement"]["anotherElement"]->object->property["element"];
echo $array["arrayElement"]
["anotherElement"]->
object
->property["element"];
Arrays, Objects and Loops
If you don't just want to access a single element you can loop over your nested array / object 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 array, but it could also be an object:
Array (
[data] => Array (
[0] => stdClass Object (
[propertyXY] => 1
)
[1] => stdClass Object (
[propertyXY] => 2
)
[2] => stdClass Object (
[propertyXY] => 3
)
)
)
If you loop over the first dimension you will get all values from the first dimension:
foreach($array as $key => $value)
Means here in the first dimension you would only have 1 element with the key($key) data and the value($value):
Array ( //Key: array
[0] => stdClass Object (
[propertyXY] => 1
)
[1] => stdClass Object (
[propertyXY] => 2
)
[2] => stdClass Object (
[propertyXY] => 3
)
)
If you loop over the second dimension you will get all values from the second dimension:
foreach($array["data"] as $key => $value)
Means here in the second dimension you would have 3 element with the keys($key) 0, 1, 2 and the values($value):
stdClass Object ( //Key: 0
[propertyXY] => 1
)
stdClass Object ( //Key: 1
[propertyXY] => 2
)
stdClass Object ( //Key: 2
[propertyXY] => 3
)
And with this you can loop through any dimension which you want no matter if it is an array or object.
Analyse var_dump() / print_r() / var_export() output
All of these 3 debug functions output the same data, just in another format or with some meta data (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 data from your array/object.
Input array:
$array = [
"key" => (object) [
"property" => [1,2,3]
]
];
var_dump() output:
array(1) {
["key"]=>
object(stdClass)#1 (1) {
["property"]=>
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
}
}
print_r() output:
Array
(
[key] => stdClass Object
(
[property] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
)
var_export() output:
array (
'key' =>
(object) array(
'property' =>
array (
0 => 1,
1 => 2,
2 => 3,
),
),
)
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".
1. We first see, that the value 2 is in an array with the key 1
// var_dump()
array(3) {
[0]=>
int(1)
[1]=>
int(2) // <-- value we want to access
[2]=>
int(3)
}
// print_r()
Array
(
[0] => 1
[1] => 2 // <-- value we want to access
[2] => 3
)
// var_export()
array (
0 => 1,
1 => 2, // <-- value we want to access
2 => 3,
)
This means we have to use [] to access the value 2 with [1], since the value has the key/index 1.
2. Next we see, that the array is assigned to a property with the name property of an object
// var_dump()
object(stdClass)#1 (1) {
["property"]=>
/* Array here */
}
// print_r()
stdClass Object
(
[property] => /* Array here */
)
// var_export()
(object) array(
'property' =>
/* Array here */
),
This means we have to use -> to access the property of the object, e.g. ->property.
So until now, we know that we have to use ->property[1].
3. And at the end we see, that the outermost is an array
// var_dump()
array(1) {
["key"]=>
/* Object & Array here */
}
// print_r()
Array
(
[key] => stdClass Object
/* Object & Array here */
)
// var_export()
array (
'key' =>
/* Object & Array here */
)
As we know that we have to access an array element with [], we see here that we have to use ["key"] to access the object. We now can put all these parts together and write:
echo $array["key"]->property[1];
And the output will be:
2
Don't let PHP troll you!
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:
Array ( [key] => HERE )
Then you are trying to access the element with:
echo $arr["key"];
But you are getting the notice:
Notice: Undefined index: key
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:
array(1) {
["</b>
key"]=>
string(4) "HERE"
}
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:
echo $arr["</b>\nkey"];
You will get your desired output:
HERE
Never trust the output of print_r() or var_dump() if you look at XML
You might have an XML file or string loaded into an object, e.g.
<?xml version="1.0" encoding="UTF-8" ?>
<rss>
<item>
<title attribute="xy" ab="xy">test</title>
</item>
</rss>
Now if you use var_dump() or print_r() you will see:
SimpleXMLElement Object
(
[item] => SimpleXMLElement Object
(
[title] => test
)
)
So as you can see you don't see the attributes of title. So as I said never trust the output of var_dump() or print_r() when you have an XML object. Always use asXML() to see the full XML file/string.
So just use one of the methods shown below:
echo $xml->asXML(); //And look into the source code
highlight_string($xml->asXML());
header ("Content-Type:text/xml");
echo $xml->asXML();
And then you will get the output:
<?xml version="1.0" encoding="UTF-8"?>
<rss>
<item>
<title attribute="xy" ab="xy">test</title>
</item>
</rss>
For more information see:
General (symbols, errors)
Reference — What does this symbol mean in PHP?
Reference - What does this error mean in PHP?
PHP parse/syntax errors; and how to solve them
Property name problems
How can I access a property with an invalid name?
How to access object properties with names like integers or invalid property names?

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
echo array_values($get_user)[0]; // 10499478683521864

If your output from print_r($var) is e.g:
Array ( [demo] => Array ( [0] => 10499478683521864 [1] => 07/22/1983 [2] => email#saya.com ) )
then do $var['demo'][0]
If the output from print_r($var) is e.g:
Array ( [0] => 10499478683521864 [1] => 07/22/1983 [2] => email#saya.com )
then do $var[0]

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:
[
'id' => 10499478683521864,
'birthday' => '07/22/1983',
'email' => 'email#saya.com',
'first_name' => 'Alan',
'gender' => 'male',
'last_name' => 'Malmsteen',
'link' => 'https://www.facebook.com/app_scoped_user_id/1049213468352864/',
'location' => (object) [
'id' => 102173722491792,
'name' => 'Jakarta, Indonesia'
],
'locale' => 'id_ID',
'middle_name' => 'El-nino',
'name' => 'Alan El-nino Malmsteen',
'timezone' => 7,
'updated_time' => '2015-05-28T04:09:50+0000',
'verified' => 1
]
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), otherwise json_decode($response).
If you try to pass $response as an object into array_values(), from PHP8 you will generate Fatal 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.
To access specific first level elements, you use "square brace" syntax with quoted string keys.
$response['id'] to access 10499478683521864
$response['gender'] to access male
$response['location'] to access (object) ['id' => 102173722491792, 'name' => 'Jakarta, Indonesia']
To access the data nested in location (second level), "arrow syntax" is required because the data is an object.
$response['location']->id to access 102173722491792
$response['location']->name to access Jakarta, Indonesia
After calling array_values() on your response, the structure is an indexed array, so use square braces with unquoted integers.
$response[0] to access 10499478683521864
$response[4] to access male
$response[7] to access (object) ['id' => 102173722491792, 'name' => 'Jakarta, Indonesia']
$response[7]->id to access 102173722491792
$response[7]->name to access Jakarta, Indonesia
When you aren't sure what data type you are working with, use var_export() or var_dump().
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)
foreach ($response as $key1 => $value1) {
if (is_scalar($value1)) {
echo "Key1: $key1, Value1: $value1\n";
} else {
foreach ($value1 as $key2 => $value2) {
echo "Key1: $key1, Key2: $key2, Value2: $value2\n";
}
}
}
Output:
Key1: id, Value1: 10499478683521864
Key1: birthday, Value1: 07/22/1983
Key1: email, Value1: email#saya.com
Key1: first_name, Value1: Alan
Key1: gender, Value1: male
Key1: last_name, Value1: Malmsteen
Key1: link, Value1: https://www.facebook.com/app_scoped_user_id/1049213468352864/
Key1: location, Key2: id, Value2: 102173722491792
Key1: location, Key2: name, Value2: Jakarta, Indonesia
Key1: locale, Value1: id_ID
Key1: middle_name, Value1: El-nino
Key1: name, Value1: Alan El-nino Malmsteen
Key1: timezone, Value1: 7
Key1: updated_time, Value1: 2015-05-28T04:09:50+0000
Key1: verified, Value1: 1

I wrote a small function for accessing properties in either arrays or objects. I use it quite a bit find it pretty handy
/**
* Access array or object values easily, with default fallback
*/
if( ! function_exists('element') )
{
function element( &$array, $key, $default = NULL )
{
// Check array first
if( is_array($array) )
{
return isset($array[$key]) ? $array[$key] : $default;
}
// Object props
if( ! is_int($key) && is_object($array) )
{
return property_exists($array, $key) ? $array->{$key} : $default;
}
// Invalid type
return NULL;
}
}

function kPrint($key,$obj){
return (gettype($obj)=="array"?(array_key_exists($key,$obj)?$obj[$key]:("<font color='red'>NA</font>")):(gettype($obj)=="object"?(property_exists($obj,$key)?$obj->$key:("<font color='red'>NA</font>")):("<font color='red'><font color='green'>:::Exception Start:::</font><br>Invalid Object/Array Passed at kPrint() Function!!<br> At : Variable => ".print_r($obj)."<br>Key => ".$key."<br> At File: <font color='blue'>".debug_backtrace()[0]['file']."</font><br> At Line : ".debug_backtrace()[0]['line']."<br><font color='green'>:::Exception End:::</font></font>")));}
//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.

Related

How to access specific variable in array [duplicate]

I have the following array and when I do print_r(array_values($get_user));, I get:
Array (
[0] => 10499478683521864
[1] => 07/22/1983
[2] => email#saya.com
[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#saya.com from the array?
To access an array or object you how to use two different operators.
Arrays
To access array elements you have to use [].
echo $array[0];
On older PHP versions, an alternative syntax using {} was also allowed:
echo $array{0};
Difference between declaring an array and accessing an array element
Defining an array and accessing an array element are two different things. So don't mix them up.
To define an array you can use array() or for PHP >=5.4 [] and you assign/set an array/-element. While when you are accessing an array element with [] as mentioned above, you get the value of an array element opposed to setting an element.
//Declaring an array
$arrayA = array ( /*Some stuff in here*/ );
$arrayB = [ /*Some stuff in here*/ ]; //Only for PHP >=5.4
//Accessing an array element
echo $array[0];
Access array element
To access a particular element in an array you can use any expression inside [] or {} which then evaluates to the key you want to access:
$array[(Any expression)]
So just be aware of what expression you use as key and how it gets interpreted by PHP:
echo $array[0]; //The key is an integer; It accesses the 0's element
echo $array["0"]; //The key is a string; It accesses the 0's element
echo $array["string"]; //The key is a string; It accesses the element with the key 'string'
echo $array[CONSTANT]; //The key is a constant and it gets replaced with the corresponding value
echo $array[cOnStAnT]; //The key is also a constant and not a string
echo $array[$anyVariable] //The key is a variable and it gets replaced with the value which is in '$anyVariable'
echo $array[functionXY()]; //The key will be the return value of the function
Access multidimensional array
If you have multiple arrays in each other you simply have a multidimensional array. To access an array element in a sub array you just have to use multiple [].
echo $array["firstSubArray"]["SecondSubArray"]["ElementFromTheSecondSubArray"]
// ├─────────────┘ ├──────────────┘ ├────────────────────────────┘
// │ │ └── 3rd Array dimension;
// │ └──────────────────── 2d Array dimension;
// └───────────────────────────────────── 1st Array dimension;
Objects
To access an object property you have to use ->.
echo $object->property;
If you have an object in another object you just have to use multiple -> to get to your object property.
echo $objectA->objectB->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.
Arrays & Objects
Now if you have arrays and objects mixed in each other you just have to look if you now access an array element or an object property and use the corresponding operator for it.
//Object
echo $object->anotherObject->propertyArray["elementOneWithAnObject"]->property;
//├────┘ ├───────────┘ ├───────────┘ ├──────────────────────┘ ├──────┘
//│ │ │ │ └── property ;
//│ │ │ └───────────────────────────── array element (object) ; Use -> To access the property 'property'
//│ │ └─────────────────────────────────────────── array (property) ; Use [] To access the array element 'elementOneWithAnObject'
//│ └────────────────────────────────────────────────────────── property (object) ; Use -> To access the property 'propertyArray'
//└────────────────────────────────────────────────────────────────── object ; Use -> To access the property 'anotherObject'
//Array
echo $array["arrayElement"]["anotherElement"]->object->property["element"];
//├───┘ ├────────────┘ ├──────────────┘ ├────┘ ├──────┘ ├───────┘
//│ │ │ │ │ └── array element ;
//│ │ │ │ └─────────── property (array) ; Use [] To access the array element 'element'
//│ │ │ └─────────────────── property (object) ; Use -> To access the property 'property'
//│ │ └────────────────────────────────────── array element (object) ; Use -> To access the property 'object'
//│ └────────────────────────────────────────────────────── array element (array) ; Use [] To access the array element 'anotherElement'
//└──────────────────────────────────────────────────────────── array ; Use [] To access the array element 'arrayElement'
I hope this gives you a rough idea how you can access arrays and objects, when they are nested in each other.
Note:
If it is called an array or object depends on the outermost part of your variable. So [new StdClass] is an array even if it has (nested) objects inside of it and $object->property = array(); is an object even if it has (nested) arrays inside.
And if you are not sure if you have an object or array, just use gettype().
Don't get yourself confused if someone uses another coding style than you:
//Both methods/styles work and access the same data
echo $object->anotherObject->propertyArray["elementOneWithAnObject"]->property;
echo $object->
anotherObject
->propertyArray
["elementOneWithAnObject"]->
property;
//Both methods/styles work and access the same data
echo $array["arrayElement"]["anotherElement"]->object->property["element"];
echo $array["arrayElement"]
["anotherElement"]->
object
->property["element"];
Arrays, Objects and Loops
If you don't just want to access a single element you can loop over your nested array / object 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 array, but it could also be an object:
Array (
[data] => Array (
[0] => stdClass Object (
[propertyXY] => 1
)
[1] => stdClass Object (
[propertyXY] => 2
)
[2] => stdClass Object (
[propertyXY] => 3
)
)
)
If you loop over the first dimension you will get all values from the first dimension:
foreach($array as $key => $value)
Means here in the first dimension you would only have 1 element with the key($key) data and the value($value):
Array ( //Key: array
[0] => stdClass Object (
[propertyXY] => 1
)
[1] => stdClass Object (
[propertyXY] => 2
)
[2] => stdClass Object (
[propertyXY] => 3
)
)
If you loop over the second dimension you will get all values from the second dimension:
foreach($array["data"] as $key => $value)
Means here in the second dimension you would have 3 element with the keys($key) 0, 1, 2 and the values($value):
stdClass Object ( //Key: 0
[propertyXY] => 1
)
stdClass Object ( //Key: 1
[propertyXY] => 2
)
stdClass Object ( //Key: 2
[propertyXY] => 3
)
And with this you can loop through any dimension which you want no matter if it is an array or object.
Analyse var_dump() / print_r() / var_export() output
All of these 3 debug functions output the same data, just in another format or with some meta data (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 data from your array/object.
Input array:
$array = [
"key" => (object) [
"property" => [1,2,3]
]
];
var_dump() output:
array(1) {
["key"]=>
object(stdClass)#1 (1) {
["property"]=>
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
}
}
print_r() output:
Array
(
[key] => stdClass Object
(
[property] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
)
var_export() output:
array (
'key' =>
(object) array(
'property' =>
array (
0 => 1,
1 => 2,
2 => 3,
),
),
)
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".
1. We first see, that the value 2 is in an array with the key 1
// var_dump()
array(3) {
[0]=>
int(1)
[1]=>
int(2) // <-- value we want to access
[2]=>
int(3)
}
// print_r()
Array
(
[0] => 1
[1] => 2 // <-- value we want to access
[2] => 3
)
// var_export()
array (
0 => 1,
1 => 2, // <-- value we want to access
2 => 3,
)
This means we have to use [] to access the value 2 with [1], since the value has the key/index 1.
2. Next we see, that the array is assigned to a property with the name property of an object
// var_dump()
object(stdClass)#1 (1) {
["property"]=>
/* Array here */
}
// print_r()
stdClass Object
(
[property] => /* Array here */
)
// var_export()
(object) array(
'property' =>
/* Array here */
),
This means we have to use -> to access the property of the object, e.g. ->property.
So until now, we know that we have to use ->property[1].
3. And at the end we see, that the outermost is an array
// var_dump()
array(1) {
["key"]=>
/* Object & Array here */
}
// print_r()
Array
(
[key] => stdClass Object
/* Object & Array here */
)
// var_export()
array (
'key' =>
/* Object & Array here */
)
As we know that we have to access an array element with [], we see here that we have to use ["key"] to access the object. We now can put all these parts together and write:
echo $array["key"]->property[1];
And the output will be:
2
Don't let PHP troll you!
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:
Array ( [key] => HERE )
Then you are trying to access the element with:
echo $arr["key"];
But you are getting the notice:
Notice: Undefined index: key
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:
array(1) {
["</b>
key"]=>
string(4) "HERE"
}
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:
echo $arr["</b>\nkey"];
You will get your desired output:
HERE
Never trust the output of print_r() or var_dump() if you look at XML
You might have an XML file or string loaded into an object, e.g.
<?xml version="1.0" encoding="UTF-8" ?>
<rss>
<item>
<title attribute="xy" ab="xy">test</title>
</item>
</rss>
Now if you use var_dump() or print_r() you will see:
SimpleXMLElement Object
(
[item] => SimpleXMLElement Object
(
[title] => test
)
)
So as you can see you don't see the attributes of title. So as I said never trust the output of var_dump() or print_r() when you have an XML object. Always use asXML() to see the full XML file/string.
So just use one of the methods shown below:
echo $xml->asXML(); //And look into the source code
highlight_string($xml->asXML());
header ("Content-Type:text/xml");
echo $xml->asXML();
And then you will get the output:
<?xml version="1.0" encoding="UTF-8"?>
<rss>
<item>
<title attribute="xy" ab="xy">test</title>
</item>
</rss>
For more information see:
General (symbols, errors)
Reference — What does this symbol mean in PHP?
Reference - What does this error mean in PHP?
PHP parse/syntax errors; and how to solve them
Property name problems
How can I access a property with an invalid name?
How to access object properties with names like integers or invalid property names?
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
echo array_values($get_user)[0]; // 10499478683521864
If your output from print_r($var) is e.g:
Array ( [demo] => Array ( [0] => 10499478683521864 [1] => 07/22/1983 [2] => email#saya.com ) )
then do $var['demo'][0]
If the output from print_r($var) is e.g:
Array ( [0] => 10499478683521864 [1] => 07/22/1983 [2] => email#saya.com )
then do $var[0]
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:
[
'id' => 10499478683521864,
'birthday' => '07/22/1983',
'email' => 'email#saya.com',
'first_name' => 'Alan',
'gender' => 'male',
'last_name' => 'Malmsteen',
'link' => 'https://www.facebook.com/app_scoped_user_id/1049213468352864/',
'location' => (object) [
'id' => 102173722491792,
'name' => 'Jakarta, Indonesia'
],
'locale' => 'id_ID',
'middle_name' => 'El-nino',
'name' => 'Alan El-nino Malmsteen',
'timezone' => 7,
'updated_time' => '2015-05-28T04:09:50+0000',
'verified' => 1
]
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), otherwise json_decode($response).
If you try to pass $response as an object into array_values(), from PHP8 you will generate Fatal 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.
To access specific first level elements, you use "square brace" syntax with quoted string keys.
$response['id'] to access 10499478683521864
$response['gender'] to access male
$response['location'] to access (object) ['id' => 102173722491792, 'name' => 'Jakarta, Indonesia']
To access the data nested in location (second level), "arrow syntax" is required because the data is an object.
$response['location']->id to access 102173722491792
$response['location']->name to access Jakarta, Indonesia
After calling array_values() on your response, the structure is an indexed array, so use square braces with unquoted integers.
$response[0] to access 10499478683521864
$response[4] to access male
$response[7] to access (object) ['id' => 102173722491792, 'name' => 'Jakarta, Indonesia']
$response[7]->id to access 102173722491792
$response[7]->name to access Jakarta, Indonesia
When you aren't sure what data type you are working with, use var_export() or var_dump().
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)
foreach ($response as $key1 => $value1) {
if (is_scalar($value1)) {
echo "Key1: $key1, Value1: $value1\n";
} else {
foreach ($value1 as $key2 => $value2) {
echo "Key1: $key1, Key2: $key2, Value2: $value2\n";
}
}
}
Output:
Key1: id, Value1: 10499478683521864
Key1: birthday, Value1: 07/22/1983
Key1: email, Value1: email#saya.com
Key1: first_name, Value1: Alan
Key1: gender, Value1: male
Key1: last_name, Value1: Malmsteen
Key1: link, Value1: https://www.facebook.com/app_scoped_user_id/1049213468352864/
Key1: location, Key2: id, Value2: 102173722491792
Key1: location, Key2: name, Value2: Jakarta, Indonesia
Key1: locale, Value1: id_ID
Key1: middle_name, Value1: El-nino
Key1: name, Value1: Alan El-nino Malmsteen
Key1: timezone, Value1: 7
Key1: updated_time, Value1: 2015-05-28T04:09:50+0000
Key1: verified, Value1: 1
I wrote a small function for accessing properties in either arrays or objects. I use it quite a bit find it pretty handy
/**
* Access array or object values easily, with default fallback
*/
if( ! function_exists('element') )
{
function element( &$array, $key, $default = NULL )
{
// Check array first
if( is_array($array) )
{
return isset($array[$key]) ? $array[$key] : $default;
}
// Object props
if( ! is_int($key) && is_object($array) )
{
return property_exists($array, $key) ? $array->{$key} : $default;
}
// Invalid type
return NULL;
}
}
function kPrint($key,$obj){
return (gettype($obj)=="array"?(array_key_exists($key,$obj)?$obj[$key]:("<font color='red'>NA</font>")):(gettype($obj)=="object"?(property_exists($obj,$key)?$obj->$key:("<font color='red'>NA</font>")):("<font color='red'><font color='green'>:::Exception Start:::</font><br>Invalid Object/Array Passed at kPrint() Function!!<br> At : Variable => ".print_r($obj)."<br>Key => ".$key."<br> At File: <font color='blue'>".debug_backtrace()[0]['file']."</font><br> At Line : ".debug_backtrace()[0]['line']."<br><font color='green'>:::Exception End:::</font></font>")));}
//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.

How to print stdClass Object [duplicate]

I have the following array and when I do print_r(array_values($get_user));, I get:
Array (
[0] => 10499478683521864
[1] => 07/22/1983
[2] => email#saya.com
[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#saya.com from the array?
To access an array or object you how to use two different operators.
Arrays
To access array elements you have to use [].
echo $array[0];
On older PHP versions, an alternative syntax using {} was also allowed:
echo $array{0};
Difference between declaring an array and accessing an array element
Defining an array and accessing an array element are two different things. So don't mix them up.
To define an array you can use array() or for PHP >=5.4 [] and you assign/set an array/-element. While when you are accessing an array element with [] as mentioned above, you get the value of an array element opposed to setting an element.
//Declaring an array
$arrayA = array ( /*Some stuff in here*/ );
$arrayB = [ /*Some stuff in here*/ ]; //Only for PHP >=5.4
//Accessing an array element
echo $array[0];
Access array element
To access a particular element in an array you can use any expression inside [] or {} which then evaluates to the key you want to access:
$array[(Any expression)]
So just be aware of what expression you use as key and how it gets interpreted by PHP:
echo $array[0]; //The key is an integer; It accesses the 0's element
echo $array["0"]; //The key is a string; It accesses the 0's element
echo $array["string"]; //The key is a string; It accesses the element with the key 'string'
echo $array[CONSTANT]; //The key is a constant and it gets replaced with the corresponding value
echo $array[cOnStAnT]; //The key is also a constant and not a string
echo $array[$anyVariable] //The key is a variable and it gets replaced with the value which is in '$anyVariable'
echo $array[functionXY()]; //The key will be the return value of the function
Access multidimensional array
If you have multiple arrays in each other you simply have a multidimensional array. To access an array element in a sub array you just have to use multiple [].
echo $array["firstSubArray"]["SecondSubArray"]["ElementFromTheSecondSubArray"]
// ├─────────────┘ ├──────────────┘ ├────────────────────────────┘
// │ │ └── 3rd Array dimension;
// │ └──────────────────── 2d Array dimension;
// └───────────────────────────────────── 1st Array dimension;
Objects
To access an object property you have to use ->.
echo $object->property;
If you have an object in another object you just have to use multiple -> to get to your object property.
echo $objectA->objectB->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.
Arrays & Objects
Now if you have arrays and objects mixed in each other you just have to look if you now access an array element or an object property and use the corresponding operator for it.
//Object
echo $object->anotherObject->propertyArray["elementOneWithAnObject"]->property;
//├────┘ ├───────────┘ ├───────────┘ ├──────────────────────┘ ├──────┘
//│ │ │ │ └── property ;
//│ │ │ └───────────────────────────── array element (object) ; Use -> To access the property 'property'
//│ │ └─────────────────────────────────────────── array (property) ; Use [] To access the array element 'elementOneWithAnObject'
//│ └────────────────────────────────────────────────────────── property (object) ; Use -> To access the property 'propertyArray'
//└────────────────────────────────────────────────────────────────── object ; Use -> To access the property 'anotherObject'
//Array
echo $array["arrayElement"]["anotherElement"]->object->property["element"];
//├───┘ ├────────────┘ ├──────────────┘ ├────┘ ├──────┘ ├───────┘
//│ │ │ │ │ └── array element ;
//│ │ │ │ └─────────── property (array) ; Use [] To access the array element 'element'
//│ │ │ └─────────────────── property (object) ; Use -> To access the property 'property'
//│ │ └────────────────────────────────────── array element (object) ; Use -> To access the property 'object'
//│ └────────────────────────────────────────────────────── array element (array) ; Use [] To access the array element 'anotherElement'
//└──────────────────────────────────────────────────────────── array ; Use [] To access the array element 'arrayElement'
I hope this gives you a rough idea how you can access arrays and objects, when they are nested in each other.
Note:
If it is called an array or object depends on the outermost part of your variable. So [new StdClass] is an array even if it has (nested) objects inside of it and $object->property = array(); is an object even if it has (nested) arrays inside.
And if you are not sure if you have an object or array, just use gettype().
Don't get yourself confused if someone uses another coding style than you:
//Both methods/styles work and access the same data
echo $object->anotherObject->propertyArray["elementOneWithAnObject"]->property;
echo $object->
anotherObject
->propertyArray
["elementOneWithAnObject"]->
property;
//Both methods/styles work and access the same data
echo $array["arrayElement"]["anotherElement"]->object->property["element"];
echo $array["arrayElement"]
["anotherElement"]->
object
->property["element"];
Arrays, Objects and Loops
If you don't just want to access a single element you can loop over your nested array / object 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 array, but it could also be an object:
Array (
[data] => Array (
[0] => stdClass Object (
[propertyXY] => 1
)
[1] => stdClass Object (
[propertyXY] => 2
)
[2] => stdClass Object (
[propertyXY] => 3
)
)
)
If you loop over the first dimension you will get all values from the first dimension:
foreach($array as $key => $value)
Means here in the first dimension you would only have 1 element with the key($key) data and the value($value):
Array ( //Key: array
[0] => stdClass Object (
[propertyXY] => 1
)
[1] => stdClass Object (
[propertyXY] => 2
)
[2] => stdClass Object (
[propertyXY] => 3
)
)
If you loop over the second dimension you will get all values from the second dimension:
foreach($array["data"] as $key => $value)
Means here in the second dimension you would have 3 element with the keys($key) 0, 1, 2 and the values($value):
stdClass Object ( //Key: 0
[propertyXY] => 1
)
stdClass Object ( //Key: 1
[propertyXY] => 2
)
stdClass Object ( //Key: 2
[propertyXY] => 3
)
And with this you can loop through any dimension which you want no matter if it is an array or object.
Analyse var_dump() / print_r() / var_export() output
All of these 3 debug functions output the same data, just in another format or with some meta data (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 data from your array/object.
Input array:
$array = [
"key" => (object) [
"property" => [1,2,3]
]
];
var_dump() output:
array(1) {
["key"]=>
object(stdClass)#1 (1) {
["property"]=>
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
}
}
print_r() output:
Array
(
[key] => stdClass Object
(
[property] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
)
var_export() output:
array (
'key' =>
(object) array(
'property' =>
array (
0 => 1,
1 => 2,
2 => 3,
),
),
)
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".
1. We first see, that the value 2 is in an array with the key 1
// var_dump()
array(3) {
[0]=>
int(1)
[1]=>
int(2) // <-- value we want to access
[2]=>
int(3)
}
// print_r()
Array
(
[0] => 1
[1] => 2 // <-- value we want to access
[2] => 3
)
// var_export()
array (
0 => 1,
1 => 2, // <-- value we want to access
2 => 3,
)
This means we have to use [] to access the value 2 with [1], since the value has the key/index 1.
2. Next we see, that the array is assigned to a property with the name property of an object
// var_dump()
object(stdClass)#1 (1) {
["property"]=>
/* Array here */
}
// print_r()
stdClass Object
(
[property] => /* Array here */
)
// var_export()
(object) array(
'property' =>
/* Array here */
),
This means we have to use -> to access the property of the object, e.g. ->property.
So until now, we know that we have to use ->property[1].
3. And at the end we see, that the outermost is an array
// var_dump()
array(1) {
["key"]=>
/* Object & Array here */
}
// print_r()
Array
(
[key] => stdClass Object
/* Object & Array here */
)
// var_export()
array (
'key' =>
/* Object & Array here */
)
As we know that we have to access an array element with [], we see here that we have to use ["key"] to access the object. We now can put all these parts together and write:
echo $array["key"]->property[1];
And the output will be:
2
Don't let PHP troll you!
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:
Array ( [key] => HERE )
Then you are trying to access the element with:
echo $arr["key"];
But you are getting the notice:
Notice: Undefined index: key
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:
array(1) {
["</b>
key"]=>
string(4) "HERE"
}
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:
echo $arr["</b>\nkey"];
You will get your desired output:
HERE
Never trust the output of print_r() or var_dump() if you look at XML
You might have an XML file or string loaded into an object, e.g.
<?xml version="1.0" encoding="UTF-8" ?>
<rss>
<item>
<title attribute="xy" ab="xy">test</title>
</item>
</rss>
Now if you use var_dump() or print_r() you will see:
SimpleXMLElement Object
(
[item] => SimpleXMLElement Object
(
[title] => test
)
)
So as you can see you don't see the attributes of title. So as I said never trust the output of var_dump() or print_r() when you have an XML object. Always use asXML() to see the full XML file/string.
So just use one of the methods shown below:
echo $xml->asXML(); //And look into the source code
highlight_string($xml->asXML());
header ("Content-Type:text/xml");
echo $xml->asXML();
And then you will get the output:
<?xml version="1.0" encoding="UTF-8"?>
<rss>
<item>
<title attribute="xy" ab="xy">test</title>
</item>
</rss>
For more information see:
General (symbols, errors)
Reference — What does this symbol mean in PHP?
Reference - What does this error mean in PHP?
PHP parse/syntax errors; and how to solve them
Property name problems
How can I access a property with an invalid name?
How to access object properties with names like integers or invalid property names?
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
echo array_values($get_user)[0]; // 10499478683521864
If your output from print_r($var) is e.g:
Array ( [demo] => Array ( [0] => 10499478683521864 [1] => 07/22/1983 [2] => email#saya.com ) )
then do $var['demo'][0]
If the output from print_r($var) is e.g:
Array ( [0] => 10499478683521864 [1] => 07/22/1983 [2] => email#saya.com )
then do $var[0]
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:
[
'id' => 10499478683521864,
'birthday' => '07/22/1983',
'email' => 'email#saya.com',
'first_name' => 'Alan',
'gender' => 'male',
'last_name' => 'Malmsteen',
'link' => 'https://www.facebook.com/app_scoped_user_id/1049213468352864/',
'location' => (object) [
'id' => 102173722491792,
'name' => 'Jakarta, Indonesia'
],
'locale' => 'id_ID',
'middle_name' => 'El-nino',
'name' => 'Alan El-nino Malmsteen',
'timezone' => 7,
'updated_time' => '2015-05-28T04:09:50+0000',
'verified' => 1
]
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), otherwise json_decode($response).
If you try to pass $response as an object into array_values(), from PHP8 you will generate Fatal 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.
To access specific first level elements, you use "square brace" syntax with quoted string keys.
$response['id'] to access 10499478683521864
$response['gender'] to access male
$response['location'] to access (object) ['id' => 102173722491792, 'name' => 'Jakarta, Indonesia']
To access the data nested in location (second level), "arrow syntax" is required because the data is an object.
$response['location']->id to access 102173722491792
$response['location']->name to access Jakarta, Indonesia
After calling array_values() on your response, the structure is an indexed array, so use square braces with unquoted integers.
$response[0] to access 10499478683521864
$response[4] to access male
$response[7] to access (object) ['id' => 102173722491792, 'name' => 'Jakarta, Indonesia']
$response[7]->id to access 102173722491792
$response[7]->name to access Jakarta, Indonesia
When you aren't sure what data type you are working with, use var_export() or var_dump().
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)
foreach ($response as $key1 => $value1) {
if (is_scalar($value1)) {
echo "Key1: $key1, Value1: $value1\n";
} else {
foreach ($value1 as $key2 => $value2) {
echo "Key1: $key1, Key2: $key2, Value2: $value2\n";
}
}
}
Output:
Key1: id, Value1: 10499478683521864
Key1: birthday, Value1: 07/22/1983
Key1: email, Value1: email#saya.com
Key1: first_name, Value1: Alan
Key1: gender, Value1: male
Key1: last_name, Value1: Malmsteen
Key1: link, Value1: https://www.facebook.com/app_scoped_user_id/1049213468352864/
Key1: location, Key2: id, Value2: 102173722491792
Key1: location, Key2: name, Value2: Jakarta, Indonesia
Key1: locale, Value1: id_ID
Key1: middle_name, Value1: El-nino
Key1: name, Value1: Alan El-nino Malmsteen
Key1: timezone, Value1: 7
Key1: updated_time, Value1: 2015-05-28T04:09:50+0000
Key1: verified, Value1: 1
I wrote a small function for accessing properties in either arrays or objects. I use it quite a bit find it pretty handy
/**
* Access array or object values easily, with default fallback
*/
if( ! function_exists('element') )
{
function element( &$array, $key, $default = NULL )
{
// Check array first
if( is_array($array) )
{
return isset($array[$key]) ? $array[$key] : $default;
}
// Object props
if( ! is_int($key) && is_object($array) )
{
return property_exists($array, $key) ? $array->{$key} : $default;
}
// Invalid type
return NULL;
}
}
function kPrint($key,$obj){
return (gettype($obj)=="array"?(array_key_exists($key,$obj)?$obj[$key]:("<font color='red'>NA</font>")):(gettype($obj)=="object"?(property_exists($obj,$key)?$obj->$key:("<font color='red'>NA</font>")):("<font color='red'><font color='green'>:::Exception Start:::</font><br>Invalid Object/Array Passed at kPrint() Function!!<br> At : Variable => ".print_r($obj)."<br>Key => ".$key."<br> At File: <font color='blue'>".debug_backtrace()[0]['file']."</font><br> At Line : ".debug_backtrace()[0]['line']."<br><font color='green'>:::Exception End:::</font></font>")));}
//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.

Access element of node of PHP stdClass object [duplicate]

I have the following array and when I do print_r(array_values($get_user));, I get:
Array (
[0] => 10499478683521864
[1] => 07/22/1983
[2] => email#saya.com
[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#saya.com from the array?
To access an array or object you how to use two different operators.
Arrays
To access array elements you have to use [].
echo $array[0];
On older PHP versions, an alternative syntax using {} was also allowed:
echo $array{0};
Difference between declaring an array and accessing an array element
Defining an array and accessing an array element are two different things. So don't mix them up.
To define an array you can use array() or for PHP >=5.4 [] and you assign/set an array/-element. While when you are accessing an array element with [] as mentioned above, you get the value of an array element opposed to setting an element.
//Declaring an array
$arrayA = array ( /*Some stuff in here*/ );
$arrayB = [ /*Some stuff in here*/ ]; //Only for PHP >=5.4
//Accessing an array element
echo $array[0];
Access array element
To access a particular element in an array you can use any expression inside [] or {} which then evaluates to the key you want to access:
$array[(Any expression)]
So just be aware of what expression you use as key and how it gets interpreted by PHP:
echo $array[0]; //The key is an integer; It accesses the 0's element
echo $array["0"]; //The key is a string; It accesses the 0's element
echo $array["string"]; //The key is a string; It accesses the element with the key 'string'
echo $array[CONSTANT]; //The key is a constant and it gets replaced with the corresponding value
echo $array[cOnStAnT]; //The key is also a constant and not a string
echo $array[$anyVariable] //The key is a variable and it gets replaced with the value which is in '$anyVariable'
echo $array[functionXY()]; //The key will be the return value of the function
Access multidimensional array
If you have multiple arrays in each other you simply have a multidimensional array. To access an array element in a sub array you just have to use multiple [].
echo $array["firstSubArray"]["SecondSubArray"]["ElementFromTheSecondSubArray"]
// ├─────────────┘ ├──────────────┘ ├────────────────────────────┘
// │ │ └── 3rd Array dimension;
// │ └──────────────────── 2d Array dimension;
// └───────────────────────────────────── 1st Array dimension;
Objects
To access an object property you have to use ->.
echo $object->property;
If you have an object in another object you just have to use multiple -> to get to your object property.
echo $objectA->objectB->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.
Arrays & Objects
Now if you have arrays and objects mixed in each other you just have to look if you now access an array element or an object property and use the corresponding operator for it.
//Object
echo $object->anotherObject->propertyArray["elementOneWithAnObject"]->property;
//├────┘ ├───────────┘ ├───────────┘ ├──────────────────────┘ ├──────┘
//│ │ │ │ └── property ;
//│ │ │ └───────────────────────────── array element (object) ; Use -> To access the property 'property'
//│ │ └─────────────────────────────────────────── array (property) ; Use [] To access the array element 'elementOneWithAnObject'
//│ └────────────────────────────────────────────────────────── property (object) ; Use -> To access the property 'propertyArray'
//└────────────────────────────────────────────────────────────────── object ; Use -> To access the property 'anotherObject'
//Array
echo $array["arrayElement"]["anotherElement"]->object->property["element"];
//├───┘ ├────────────┘ ├──────────────┘ ├────┘ ├──────┘ ├───────┘
//│ │ │ │ │ └── array element ;
//│ │ │ │ └─────────── property (array) ; Use [] To access the array element 'element'
//│ │ │ └─────────────────── property (object) ; Use -> To access the property 'property'
//│ │ └────────────────────────────────────── array element (object) ; Use -> To access the property 'object'
//│ └────────────────────────────────────────────────────── array element (array) ; Use [] To access the array element 'anotherElement'
//└──────────────────────────────────────────────────────────── array ; Use [] To access the array element 'arrayElement'
I hope this gives you a rough idea how you can access arrays and objects, when they are nested in each other.
Note:
If it is called an array or object depends on the outermost part of your variable. So [new StdClass] is an array even if it has (nested) objects inside of it and $object->property = array(); is an object even if it has (nested) arrays inside.
And if you are not sure if you have an object or array, just use gettype().
Don't get yourself confused if someone uses another coding style than you:
//Both methods/styles work and access the same data
echo $object->anotherObject->propertyArray["elementOneWithAnObject"]->property;
echo $object->
anotherObject
->propertyArray
["elementOneWithAnObject"]->
property;
//Both methods/styles work and access the same data
echo $array["arrayElement"]["anotherElement"]->object->property["element"];
echo $array["arrayElement"]
["anotherElement"]->
object
->property["element"];
Arrays, Objects and Loops
If you don't just want to access a single element you can loop over your nested array / object 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 array, but it could also be an object:
Array (
[data] => Array (
[0] => stdClass Object (
[propertyXY] => 1
)
[1] => stdClass Object (
[propertyXY] => 2
)
[2] => stdClass Object (
[propertyXY] => 3
)
)
)
If you loop over the first dimension you will get all values from the first dimension:
foreach($array as $key => $value)
Means here in the first dimension you would only have 1 element with the key($key) data and the value($value):
Array ( //Key: array
[0] => stdClass Object (
[propertyXY] => 1
)
[1] => stdClass Object (
[propertyXY] => 2
)
[2] => stdClass Object (
[propertyXY] => 3
)
)
If you loop over the second dimension you will get all values from the second dimension:
foreach($array["data"] as $key => $value)
Means here in the second dimension you would have 3 element with the keys($key) 0, 1, 2 and the values($value):
stdClass Object ( //Key: 0
[propertyXY] => 1
)
stdClass Object ( //Key: 1
[propertyXY] => 2
)
stdClass Object ( //Key: 2
[propertyXY] => 3
)
And with this you can loop through any dimension which you want no matter if it is an array or object.
Analyse var_dump() / print_r() / var_export() output
All of these 3 debug functions output the same data, just in another format or with some meta data (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 data from your array/object.
Input array:
$array = [
"key" => (object) [
"property" => [1,2,3]
]
];
var_dump() output:
array(1) {
["key"]=>
object(stdClass)#1 (1) {
["property"]=>
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
}
}
print_r() output:
Array
(
[key] => stdClass Object
(
[property] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
)
var_export() output:
array (
'key' =>
(object) array(
'property' =>
array (
0 => 1,
1 => 2,
2 => 3,
),
),
)
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".
1. We first see, that the value 2 is in an array with the key 1
// var_dump()
array(3) {
[0]=>
int(1)
[1]=>
int(2) // <-- value we want to access
[2]=>
int(3)
}
// print_r()
Array
(
[0] => 1
[1] => 2 // <-- value we want to access
[2] => 3
)
// var_export()
array (
0 => 1,
1 => 2, // <-- value we want to access
2 => 3,
)
This means we have to use [] to access the value 2 with [1], since the value has the key/index 1.
2. Next we see, that the array is assigned to a property with the name property of an object
// var_dump()
object(stdClass)#1 (1) {
["property"]=>
/* Array here */
}
// print_r()
stdClass Object
(
[property] => /* Array here */
)
// var_export()
(object) array(
'property' =>
/* Array here */
),
This means we have to use -> to access the property of the object, e.g. ->property.
So until now, we know that we have to use ->property[1].
3. And at the end we see, that the outermost is an array
// var_dump()
array(1) {
["key"]=>
/* Object & Array here */
}
// print_r()
Array
(
[key] => stdClass Object
/* Object & Array here */
)
// var_export()
array (
'key' =>
/* Object & Array here */
)
As we know that we have to access an array element with [], we see here that we have to use ["key"] to access the object. We now can put all these parts together and write:
echo $array["key"]->property[1];
And the output will be:
2
Don't let PHP troll you!
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:
Array ( [key] => HERE )
Then you are trying to access the element with:
echo $arr["key"];
But you are getting the notice:
Notice: Undefined index: key
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:
array(1) {
["</b>
key"]=>
string(4) "HERE"
}
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:
echo $arr["</b>\nkey"];
You will get your desired output:
HERE
Never trust the output of print_r() or var_dump() if you look at XML
You might have an XML file or string loaded into an object, e.g.
<?xml version="1.0" encoding="UTF-8" ?>
<rss>
<item>
<title attribute="xy" ab="xy">test</title>
</item>
</rss>
Now if you use var_dump() or print_r() you will see:
SimpleXMLElement Object
(
[item] => SimpleXMLElement Object
(
[title] => test
)
)
So as you can see you don't see the attributes of title. So as I said never trust the output of var_dump() or print_r() when you have an XML object. Always use asXML() to see the full XML file/string.
So just use one of the methods shown below:
echo $xml->asXML(); //And look into the source code
highlight_string($xml->asXML());
header ("Content-Type:text/xml");
echo $xml->asXML();
And then you will get the output:
<?xml version="1.0" encoding="UTF-8"?>
<rss>
<item>
<title attribute="xy" ab="xy">test</title>
</item>
</rss>
For more information see:
General (symbols, errors)
Reference — What does this symbol mean in PHP?
Reference - What does this error mean in PHP?
PHP parse/syntax errors; and how to solve them
Property name problems
How can I access a property with an invalid name?
How to access object properties with names like integers or invalid property names?
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
echo array_values($get_user)[0]; // 10499478683521864
If your output from print_r($var) is e.g:
Array ( [demo] => Array ( [0] => 10499478683521864 [1] => 07/22/1983 [2] => email#saya.com ) )
then do $var['demo'][0]
If the output from print_r($var) is e.g:
Array ( [0] => 10499478683521864 [1] => 07/22/1983 [2] => email#saya.com )
then do $var[0]
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:
[
'id' => 10499478683521864,
'birthday' => '07/22/1983',
'email' => 'email#saya.com',
'first_name' => 'Alan',
'gender' => 'male',
'last_name' => 'Malmsteen',
'link' => 'https://www.facebook.com/app_scoped_user_id/1049213468352864/',
'location' => (object) [
'id' => 102173722491792,
'name' => 'Jakarta, Indonesia'
],
'locale' => 'id_ID',
'middle_name' => 'El-nino',
'name' => 'Alan El-nino Malmsteen',
'timezone' => 7,
'updated_time' => '2015-05-28T04:09:50+0000',
'verified' => 1
]
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), otherwise json_decode($response).
If you try to pass $response as an object into array_values(), from PHP8 you will generate Fatal 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.
To access specific first level elements, you use "square brace" syntax with quoted string keys.
$response['id'] to access 10499478683521864
$response['gender'] to access male
$response['location'] to access (object) ['id' => 102173722491792, 'name' => 'Jakarta, Indonesia']
To access the data nested in location (second level), "arrow syntax" is required because the data is an object.
$response['location']->id to access 102173722491792
$response['location']->name to access Jakarta, Indonesia
After calling array_values() on your response, the structure is an indexed array, so use square braces with unquoted integers.
$response[0] to access 10499478683521864
$response[4] to access male
$response[7] to access (object) ['id' => 102173722491792, 'name' => 'Jakarta, Indonesia']
$response[7]->id to access 102173722491792
$response[7]->name to access Jakarta, Indonesia
When you aren't sure what data type you are working with, use var_export() or var_dump().
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)
foreach ($response as $key1 => $value1) {
if (is_scalar($value1)) {
echo "Key1: $key1, Value1: $value1\n";
} else {
foreach ($value1 as $key2 => $value2) {
echo "Key1: $key1, Key2: $key2, Value2: $value2\n";
}
}
}
Output:
Key1: id, Value1: 10499478683521864
Key1: birthday, Value1: 07/22/1983
Key1: email, Value1: email#saya.com
Key1: first_name, Value1: Alan
Key1: gender, Value1: male
Key1: last_name, Value1: Malmsteen
Key1: link, Value1: https://www.facebook.com/app_scoped_user_id/1049213468352864/
Key1: location, Key2: id, Value2: 102173722491792
Key1: location, Key2: name, Value2: Jakarta, Indonesia
Key1: locale, Value1: id_ID
Key1: middle_name, Value1: El-nino
Key1: name, Value1: Alan El-nino Malmsteen
Key1: timezone, Value1: 7
Key1: updated_time, Value1: 2015-05-28T04:09:50+0000
Key1: verified, Value1: 1
I wrote a small function for accessing properties in either arrays or objects. I use it quite a bit find it pretty handy
/**
* Access array or object values easily, with default fallback
*/
if( ! function_exists('element') )
{
function element( &$array, $key, $default = NULL )
{
// Check array first
if( is_array($array) )
{
return isset($array[$key]) ? $array[$key] : $default;
}
// Object props
if( ! is_int($key) && is_object($array) )
{
return property_exists($array, $key) ? $array->{$key} : $default;
}
// Invalid type
return NULL;
}
}
function kPrint($key,$obj){
return (gettype($obj)=="array"?(array_key_exists($key,$obj)?$obj[$key]:("<font color='red'>NA</font>")):(gettype($obj)=="object"?(property_exists($obj,$key)?$obj->$key:("<font color='red'>NA</font>")):("<font color='red'><font color='green'>:::Exception Start:::</font><br>Invalid Object/Array Passed at kPrint() Function!!<br> At : Variable => ".print_r($obj)."<br>Key => ".$key."<br> At File: <font color='blue'>".debug_backtrace()[0]['file']."</font><br> At Line : ".debug_backtrace()[0]['line']."<br><font color='green'>:::Exception End:::</font></font>")));}
//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.

Pulling data from array with object [duplicate]

I have the following array and when I do print_r(array_values($get_user));, I get:
Array (
[0] => 10499478683521864
[1] => 07/22/1983
[2] => email#saya.com
[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#saya.com from the array?
To access an array or object you how to use two different operators.
Arrays
To access array elements you have to use [].
echo $array[0];
On older PHP versions, an alternative syntax using {} was also allowed:
echo $array{0};
Difference between declaring an array and accessing an array element
Defining an array and accessing an array element are two different things. So don't mix them up.
To define an array you can use array() or for PHP >=5.4 [] and you assign/set an array/-element. While when you are accessing an array element with [] as mentioned above, you get the value of an array element opposed to setting an element.
//Declaring an array
$arrayA = array ( /*Some stuff in here*/ );
$arrayB = [ /*Some stuff in here*/ ]; //Only for PHP >=5.4
//Accessing an array element
echo $array[0];
Access array element
To access a particular element in an array you can use any expression inside [] or {} which then evaluates to the key you want to access:
$array[(Any expression)]
So just be aware of what expression you use as key and how it gets interpreted by PHP:
echo $array[0]; //The key is an integer; It accesses the 0's element
echo $array["0"]; //The key is a string; It accesses the 0's element
echo $array["string"]; //The key is a string; It accesses the element with the key 'string'
echo $array[CONSTANT]; //The key is a constant and it gets replaced with the corresponding value
echo $array[cOnStAnT]; //The key is also a constant and not a string
echo $array[$anyVariable] //The key is a variable and it gets replaced with the value which is in '$anyVariable'
echo $array[functionXY()]; //The key will be the return value of the function
Access multidimensional array
If you have multiple arrays in each other you simply have a multidimensional array. To access an array element in a sub array you just have to use multiple [].
echo $array["firstSubArray"]["SecondSubArray"]["ElementFromTheSecondSubArray"]
// ├─────────────┘ ├──────────────┘ ├────────────────────────────┘
// │ │ └── 3rd Array dimension;
// │ └──────────────────── 2d Array dimension;
// └───────────────────────────────────── 1st Array dimension;
Objects
To access an object property you have to use ->.
echo $object->property;
If you have an object in another object you just have to use multiple -> to get to your object property.
echo $objectA->objectB->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.
Arrays & Objects
Now if you have arrays and objects mixed in each other you just have to look if you now access an array element or an object property and use the corresponding operator for it.
//Object
echo $object->anotherObject->propertyArray["elementOneWithAnObject"]->property;
//├────┘ ├───────────┘ ├───────────┘ ├──────────────────────┘ ├──────┘
//│ │ │ │ └── property ;
//│ │ │ └───────────────────────────── array element (object) ; Use -> To access the property 'property'
//│ │ └─────────────────────────────────────────── array (property) ; Use [] To access the array element 'elementOneWithAnObject'
//│ └────────────────────────────────────────────────────────── property (object) ; Use -> To access the property 'propertyArray'
//└────────────────────────────────────────────────────────────────── object ; Use -> To access the property 'anotherObject'
//Array
echo $array["arrayElement"]["anotherElement"]->object->property["element"];
//├───┘ ├────────────┘ ├──────────────┘ ├────┘ ├──────┘ ├───────┘
//│ │ │ │ │ └── array element ;
//│ │ │ │ └─────────── property (array) ; Use [] To access the array element 'element'
//│ │ │ └─────────────────── property (object) ; Use -> To access the property 'property'
//│ │ └────────────────────────────────────── array element (object) ; Use -> To access the property 'object'
//│ └────────────────────────────────────────────────────── array element (array) ; Use [] To access the array element 'anotherElement'
//└──────────────────────────────────────────────────────────── array ; Use [] To access the array element 'arrayElement'
I hope this gives you a rough idea how you can access arrays and objects, when they are nested in each other.
Note:
If it is called an array or object depends on the outermost part of your variable. So [new StdClass] is an array even if it has (nested) objects inside of it and $object->property = array(); is an object even if it has (nested) arrays inside.
And if you are not sure if you have an object or array, just use gettype().
Don't get yourself confused if someone uses another coding style than you:
//Both methods/styles work and access the same data
echo $object->anotherObject->propertyArray["elementOneWithAnObject"]->property;
echo $object->
anotherObject
->propertyArray
["elementOneWithAnObject"]->
property;
//Both methods/styles work and access the same data
echo $array["arrayElement"]["anotherElement"]->object->property["element"];
echo $array["arrayElement"]
["anotherElement"]->
object
->property["element"];
Arrays, Objects and Loops
If you don't just want to access a single element you can loop over your nested array / object 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 array, but it could also be an object:
Array (
[data] => Array (
[0] => stdClass Object (
[propertyXY] => 1
)
[1] => stdClass Object (
[propertyXY] => 2
)
[2] => stdClass Object (
[propertyXY] => 3
)
)
)
If you loop over the first dimension you will get all values from the first dimension:
foreach($array as $key => $value)
Means here in the first dimension you would only have 1 element with the key($key) data and the value($value):
Array ( //Key: array
[0] => stdClass Object (
[propertyXY] => 1
)
[1] => stdClass Object (
[propertyXY] => 2
)
[2] => stdClass Object (
[propertyXY] => 3
)
)
If you loop over the second dimension you will get all values from the second dimension:
foreach($array["data"] as $key => $value)
Means here in the second dimension you would have 3 element with the keys($key) 0, 1, 2 and the values($value):
stdClass Object ( //Key: 0
[propertyXY] => 1
)
stdClass Object ( //Key: 1
[propertyXY] => 2
)
stdClass Object ( //Key: 2
[propertyXY] => 3
)
And with this you can loop through any dimension which you want no matter if it is an array or object.
Analyse var_dump() / print_r() / var_export() output
All of these 3 debug functions output the same data, just in another format or with some meta data (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 data from your array/object.
Input array:
$array = [
"key" => (object) [
"property" => [1,2,3]
]
];
var_dump() output:
array(1) {
["key"]=>
object(stdClass)#1 (1) {
["property"]=>
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
}
}
print_r() output:
Array
(
[key] => stdClass Object
(
[property] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
)
var_export() output:
array (
'key' =>
(object) array(
'property' =>
array (
0 => 1,
1 => 2,
2 => 3,
),
),
)
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".
1. We first see, that the value 2 is in an array with the key 1
// var_dump()
array(3) {
[0]=>
int(1)
[1]=>
int(2) // <-- value we want to access
[2]=>
int(3)
}
// print_r()
Array
(
[0] => 1
[1] => 2 // <-- value we want to access
[2] => 3
)
// var_export()
array (
0 => 1,
1 => 2, // <-- value we want to access
2 => 3,
)
This means we have to use [] to access the value 2 with [1], since the value has the key/index 1.
2. Next we see, that the array is assigned to a property with the name property of an object
// var_dump()
object(stdClass)#1 (1) {
["property"]=>
/* Array here */
}
// print_r()
stdClass Object
(
[property] => /* Array here */
)
// var_export()
(object) array(
'property' =>
/* Array here */
),
This means we have to use -> to access the property of the object, e.g. ->property.
So until now, we know that we have to use ->property[1].
3. And at the end we see, that the outermost is an array
// var_dump()
array(1) {
["key"]=>
/* Object & Array here */
}
// print_r()
Array
(
[key] => stdClass Object
/* Object & Array here */
)
// var_export()
array (
'key' =>
/* Object & Array here */
)
As we know that we have to access an array element with [], we see here that we have to use ["key"] to access the object. We now can put all these parts together and write:
echo $array["key"]->property[1];
And the output will be:
2
Don't let PHP troll you!
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:
Array ( [key] => HERE )
Then you are trying to access the element with:
echo $arr["key"];
But you are getting the notice:
Notice: Undefined index: key
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:
array(1) {
["</b>
key"]=>
string(4) "HERE"
}
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:
echo $arr["</b>\nkey"];
You will get your desired output:
HERE
Never trust the output of print_r() or var_dump() if you look at XML
You might have an XML file or string loaded into an object, e.g.
<?xml version="1.0" encoding="UTF-8" ?>
<rss>
<item>
<title attribute="xy" ab="xy">test</title>
</item>
</rss>
Now if you use var_dump() or print_r() you will see:
SimpleXMLElement Object
(
[item] => SimpleXMLElement Object
(
[title] => test
)
)
So as you can see you don't see the attributes of title. So as I said never trust the output of var_dump() or print_r() when you have an XML object. Always use asXML() to see the full XML file/string.
So just use one of the methods shown below:
echo $xml->asXML(); //And look into the source code
highlight_string($xml->asXML());
header ("Content-Type:text/xml");
echo $xml->asXML();
And then you will get the output:
<?xml version="1.0" encoding="UTF-8"?>
<rss>
<item>
<title attribute="xy" ab="xy">test</title>
</item>
</rss>
For more information see:
General (symbols, errors)
Reference — What does this symbol mean in PHP?
Reference - What does this error mean in PHP?
PHP parse/syntax errors; and how to solve them
Property name problems
How can I access a property with an invalid name?
How to access object properties with names like integers or invalid property names?
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
echo array_values($get_user)[0]; // 10499478683521864
If your output from print_r($var) is e.g:
Array ( [demo] => Array ( [0] => 10499478683521864 [1] => 07/22/1983 [2] => email#saya.com ) )
then do $var['demo'][0]
If the output from print_r($var) is e.g:
Array ( [0] => 10499478683521864 [1] => 07/22/1983 [2] => email#saya.com )
then do $var[0]
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:
[
'id' => 10499478683521864,
'birthday' => '07/22/1983',
'email' => 'email#saya.com',
'first_name' => 'Alan',
'gender' => 'male',
'last_name' => 'Malmsteen',
'link' => 'https://www.facebook.com/app_scoped_user_id/1049213468352864/',
'location' => (object) [
'id' => 102173722491792,
'name' => 'Jakarta, Indonesia'
],
'locale' => 'id_ID',
'middle_name' => 'El-nino',
'name' => 'Alan El-nino Malmsteen',
'timezone' => 7,
'updated_time' => '2015-05-28T04:09:50+0000',
'verified' => 1
]
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), otherwise json_decode($response).
If you try to pass $response as an object into array_values(), from PHP8 you will generate Fatal 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.
To access specific first level elements, you use "square brace" syntax with quoted string keys.
$response['id'] to access 10499478683521864
$response['gender'] to access male
$response['location'] to access (object) ['id' => 102173722491792, 'name' => 'Jakarta, Indonesia']
To access the data nested in location (second level), "arrow syntax" is required because the data is an object.
$response['location']->id to access 102173722491792
$response['location']->name to access Jakarta, Indonesia
After calling array_values() on your response, the structure is an indexed array, so use square braces with unquoted integers.
$response[0] to access 10499478683521864
$response[4] to access male
$response[7] to access (object) ['id' => 102173722491792, 'name' => 'Jakarta, Indonesia']
$response[7]->id to access 102173722491792
$response[7]->name to access Jakarta, Indonesia
When you aren't sure what data type you are working with, use var_export() or var_dump().
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)
foreach ($response as $key1 => $value1) {
if (is_scalar($value1)) {
echo "Key1: $key1, Value1: $value1\n";
} else {
foreach ($value1 as $key2 => $value2) {
echo "Key1: $key1, Key2: $key2, Value2: $value2\n";
}
}
}
Output:
Key1: id, Value1: 10499478683521864
Key1: birthday, Value1: 07/22/1983
Key1: email, Value1: email#saya.com
Key1: first_name, Value1: Alan
Key1: gender, Value1: male
Key1: last_name, Value1: Malmsteen
Key1: link, Value1: https://www.facebook.com/app_scoped_user_id/1049213468352864/
Key1: location, Key2: id, Value2: 102173722491792
Key1: location, Key2: name, Value2: Jakarta, Indonesia
Key1: locale, Value1: id_ID
Key1: middle_name, Value1: El-nino
Key1: name, Value1: Alan El-nino Malmsteen
Key1: timezone, Value1: 7
Key1: updated_time, Value1: 2015-05-28T04:09:50+0000
Key1: verified, Value1: 1
I wrote a small function for accessing properties in either arrays or objects. I use it quite a bit find it pretty handy
/**
* Access array or object values easily, with default fallback
*/
if( ! function_exists('element') )
{
function element( &$array, $key, $default = NULL )
{
// Check array first
if( is_array($array) )
{
return isset($array[$key]) ? $array[$key] : $default;
}
// Object props
if( ! is_int($key) && is_object($array) )
{
return property_exists($array, $key) ? $array->{$key} : $default;
}
// Invalid type
return NULL;
}
}
function kPrint($key,$obj){
return (gettype($obj)=="array"?(array_key_exists($key,$obj)?$obj[$key]:("<font color='red'>NA</font>")):(gettype($obj)=="object"?(property_exists($obj,$key)?$obj->$key:("<font color='red'>NA</font>")):("<font color='red'><font color='green'>:::Exception Start:::</font><br>Invalid Object/Array Passed at kPrint() Function!!<br> At : Variable => ".print_r($obj)."<br>Key => ".$key."<br> At File: <font color='blue'>".debug_backtrace()[0]['file']."</font><br> At Line : ".debug_backtrace()[0]['line']."<br><font color='green'>:::Exception End:::</font></font>")));}
//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.

how do I properly access the array returned from PDO::FETCH_ASSOC? [duplicate]

I have the following array and when I do print_r(array_values($get_user));, I get:
Array (
[0] => 10499478683521864
[1] => 07/22/1983
[2] => email#saya.com
[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#saya.com from the array?
To access an array or object you how to use two different operators.
Arrays
To access array elements you have to use [].
echo $array[0];
On older PHP versions, an alternative syntax using {} was also allowed:
echo $array{0};
Difference between declaring an array and accessing an array element
Defining an array and accessing an array element are two different things. So don't mix them up.
To define an array you can use array() or for PHP >=5.4 [] and you assign/set an array/-element. While when you are accessing an array element with [] as mentioned above, you get the value of an array element opposed to setting an element.
//Declaring an array
$arrayA = array ( /*Some stuff in here*/ );
$arrayB = [ /*Some stuff in here*/ ]; //Only for PHP >=5.4
//Accessing an array element
echo $array[0];
Access array element
To access a particular element in an array you can use any expression inside [] or {} which then evaluates to the key you want to access:
$array[(Any expression)]
So just be aware of what expression you use as key and how it gets interpreted by PHP:
echo $array[0]; //The key is an integer; It accesses the 0's element
echo $array["0"]; //The key is a string; It accesses the 0's element
echo $array["string"]; //The key is a string; It accesses the element with the key 'string'
echo $array[CONSTANT]; //The key is a constant and it gets replaced with the corresponding value
echo $array[cOnStAnT]; //The key is also a constant and not a string
echo $array[$anyVariable] //The key is a variable and it gets replaced with the value which is in '$anyVariable'
echo $array[functionXY()]; //The key will be the return value of the function
Access multidimensional array
If you have multiple arrays in each other you simply have a multidimensional array. To access an array element in a sub array you just have to use multiple [].
echo $array["firstSubArray"]["SecondSubArray"]["ElementFromTheSecondSubArray"]
// ├─────────────┘ ├──────────────┘ ├────────────────────────────┘
// │ │ └── 3rd Array dimension;
// │ └──────────────────── 2d Array dimension;
// └───────────────────────────────────── 1st Array dimension;
Objects
To access an object property you have to use ->.
echo $object->property;
If you have an object in another object you just have to use multiple -> to get to your object property.
echo $objectA->objectB->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.
Arrays & Objects
Now if you have arrays and objects mixed in each other you just have to look if you now access an array element or an object property and use the corresponding operator for it.
//Object
echo $object->anotherObject->propertyArray["elementOneWithAnObject"]->property;
//├────┘ ├───────────┘ ├───────────┘ ├──────────────────────┘ ├──────┘
//│ │ │ │ └── property ;
//│ │ │ └───────────────────────────── array element (object) ; Use -> To access the property 'property'
//│ │ └─────────────────────────────────────────── array (property) ; Use [] To access the array element 'elementOneWithAnObject'
//│ └────────────────────────────────────────────────────────── property (object) ; Use -> To access the property 'propertyArray'
//└────────────────────────────────────────────────────────────────── object ; Use -> To access the property 'anotherObject'
//Array
echo $array["arrayElement"]["anotherElement"]->object->property["element"];
//├───┘ ├────────────┘ ├──────────────┘ ├────┘ ├──────┘ ├───────┘
//│ │ │ │ │ └── array element ;
//│ │ │ │ └─────────── property (array) ; Use [] To access the array element 'element'
//│ │ │ └─────────────────── property (object) ; Use -> To access the property 'property'
//│ │ └────────────────────────────────────── array element (object) ; Use -> To access the property 'object'
//│ └────────────────────────────────────────────────────── array element (array) ; Use [] To access the array element 'anotherElement'
//└──────────────────────────────────────────────────────────── array ; Use [] To access the array element 'arrayElement'
I hope this gives you a rough idea how you can access arrays and objects, when they are nested in each other.
Note:
If it is called an array or object depends on the outermost part of your variable. So [new StdClass] is an array even if it has (nested) objects inside of it and $object->property = array(); is an object even if it has (nested) arrays inside.
And if you are not sure if you have an object or array, just use gettype().
Don't get yourself confused if someone uses another coding style than you:
//Both methods/styles work and access the same data
echo $object->anotherObject->propertyArray["elementOneWithAnObject"]->property;
echo $object->
anotherObject
->propertyArray
["elementOneWithAnObject"]->
property;
//Both methods/styles work and access the same data
echo $array["arrayElement"]["anotherElement"]->object->property["element"];
echo $array["arrayElement"]
["anotherElement"]->
object
->property["element"];
Arrays, Objects and Loops
If you don't just want to access a single element you can loop over your nested array / object 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 array, but it could also be an object:
Array (
[data] => Array (
[0] => stdClass Object (
[propertyXY] => 1
)
[1] => stdClass Object (
[propertyXY] => 2
)
[2] => stdClass Object (
[propertyXY] => 3
)
)
)
If you loop over the first dimension you will get all values from the first dimension:
foreach($array as $key => $value)
Means here in the first dimension you would only have 1 element with the key($key) data and the value($value):
Array ( //Key: array
[0] => stdClass Object (
[propertyXY] => 1
)
[1] => stdClass Object (
[propertyXY] => 2
)
[2] => stdClass Object (
[propertyXY] => 3
)
)
If you loop over the second dimension you will get all values from the second dimension:
foreach($array["data"] as $key => $value)
Means here in the second dimension you would have 3 element with the keys($key) 0, 1, 2 and the values($value):
stdClass Object ( //Key: 0
[propertyXY] => 1
)
stdClass Object ( //Key: 1
[propertyXY] => 2
)
stdClass Object ( //Key: 2
[propertyXY] => 3
)
And with this you can loop through any dimension which you want no matter if it is an array or object.
Analyse var_dump() / print_r() / var_export() output
All of these 3 debug functions output the same data, just in another format or with some meta data (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 data from your array/object.
Input array:
$array = [
"key" => (object) [
"property" => [1,2,3]
]
];
var_dump() output:
array(1) {
["key"]=>
object(stdClass)#1 (1) {
["property"]=>
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
}
}
print_r() output:
Array
(
[key] => stdClass Object
(
[property] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
)
var_export() output:
array (
'key' =>
(object) array(
'property' =>
array (
0 => 1,
1 => 2,
2 => 3,
),
),
)
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".
1. We first see, that the value 2 is in an array with the key 1
// var_dump()
array(3) {
[0]=>
int(1)
[1]=>
int(2) // <-- value we want to access
[2]=>
int(3)
}
// print_r()
Array
(
[0] => 1
[1] => 2 // <-- value we want to access
[2] => 3
)
// var_export()
array (
0 => 1,
1 => 2, // <-- value we want to access
2 => 3,
)
This means we have to use [] to access the value 2 with [1], since the value has the key/index 1.
2. Next we see, that the array is assigned to a property with the name property of an object
// var_dump()
object(stdClass)#1 (1) {
["property"]=>
/* Array here */
}
// print_r()
stdClass Object
(
[property] => /* Array here */
)
// var_export()
(object) array(
'property' =>
/* Array here */
),
This means we have to use -> to access the property of the object, e.g. ->property.
So until now, we know that we have to use ->property[1].
3. And at the end we see, that the outermost is an array
// var_dump()
array(1) {
["key"]=>
/* Object & Array here */
}
// print_r()
Array
(
[key] => stdClass Object
/* Object & Array here */
)
// var_export()
array (
'key' =>
/* Object & Array here */
)
As we know that we have to access an array element with [], we see here that we have to use ["key"] to access the object. We now can put all these parts together and write:
echo $array["key"]->property[1];
And the output will be:
2
Don't let PHP troll you!
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:
Array ( [key] => HERE )
Then you are trying to access the element with:
echo $arr["key"];
But you are getting the notice:
Notice: Undefined index: key
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:
array(1) {
["</b>
key"]=>
string(4) "HERE"
}
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:
echo $arr["</b>\nkey"];
You will get your desired output:
HERE
Never trust the output of print_r() or var_dump() if you look at XML
You might have an XML file or string loaded into an object, e.g.
<?xml version="1.0" encoding="UTF-8" ?>
<rss>
<item>
<title attribute="xy" ab="xy">test</title>
</item>
</rss>
Now if you use var_dump() or print_r() you will see:
SimpleXMLElement Object
(
[item] => SimpleXMLElement Object
(
[title] => test
)
)
So as you can see you don't see the attributes of title. So as I said never trust the output of var_dump() or print_r() when you have an XML object. Always use asXML() to see the full XML file/string.
So just use one of the methods shown below:
echo $xml->asXML(); //And look into the source code
highlight_string($xml->asXML());
header ("Content-Type:text/xml");
echo $xml->asXML();
And then you will get the output:
<?xml version="1.0" encoding="UTF-8"?>
<rss>
<item>
<title attribute="xy" ab="xy">test</title>
</item>
</rss>
For more information see:
General (symbols, errors)
Reference — What does this symbol mean in PHP?
Reference - What does this error mean in PHP?
PHP parse/syntax errors; and how to solve them
Property name problems
How can I access a property with an invalid name?
How to access object properties with names like integers or invalid property names?
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
echo array_values($get_user)[0]; // 10499478683521864
If your output from print_r($var) is e.g:
Array ( [demo] => Array ( [0] => 10499478683521864 [1] => 07/22/1983 [2] => email#saya.com ) )
then do $var['demo'][0]
If the output from print_r($var) is e.g:
Array ( [0] => 10499478683521864 [1] => 07/22/1983 [2] => email#saya.com )
then do $var[0]
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:
[
'id' => 10499478683521864,
'birthday' => '07/22/1983',
'email' => 'email#saya.com',
'first_name' => 'Alan',
'gender' => 'male',
'last_name' => 'Malmsteen',
'link' => 'https://www.facebook.com/app_scoped_user_id/1049213468352864/',
'location' => (object) [
'id' => 102173722491792,
'name' => 'Jakarta, Indonesia'
],
'locale' => 'id_ID',
'middle_name' => 'El-nino',
'name' => 'Alan El-nino Malmsteen',
'timezone' => 7,
'updated_time' => '2015-05-28T04:09:50+0000',
'verified' => 1
]
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), otherwise json_decode($response).
If you try to pass $response as an object into array_values(), from PHP8 you will generate Fatal 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.
To access specific first level elements, you use "square brace" syntax with quoted string keys.
$response['id'] to access 10499478683521864
$response['gender'] to access male
$response['location'] to access (object) ['id' => 102173722491792, 'name' => 'Jakarta, Indonesia']
To access the data nested in location (second level), "arrow syntax" is required because the data is an object.
$response['location']->id to access 102173722491792
$response['location']->name to access Jakarta, Indonesia
After calling array_values() on your response, the structure is an indexed array, so use square braces with unquoted integers.
$response[0] to access 10499478683521864
$response[4] to access male
$response[7] to access (object) ['id' => 102173722491792, 'name' => 'Jakarta, Indonesia']
$response[7]->id to access 102173722491792
$response[7]->name to access Jakarta, Indonesia
When you aren't sure what data type you are working with, use var_export() or var_dump().
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)
foreach ($response as $key1 => $value1) {
if (is_scalar($value1)) {
echo "Key1: $key1, Value1: $value1\n";
} else {
foreach ($value1 as $key2 => $value2) {
echo "Key1: $key1, Key2: $key2, Value2: $value2\n";
}
}
}
Output:
Key1: id, Value1: 10499478683521864
Key1: birthday, Value1: 07/22/1983
Key1: email, Value1: email#saya.com
Key1: first_name, Value1: Alan
Key1: gender, Value1: male
Key1: last_name, Value1: Malmsteen
Key1: link, Value1: https://www.facebook.com/app_scoped_user_id/1049213468352864/
Key1: location, Key2: id, Value2: 102173722491792
Key1: location, Key2: name, Value2: Jakarta, Indonesia
Key1: locale, Value1: id_ID
Key1: middle_name, Value1: El-nino
Key1: name, Value1: Alan El-nino Malmsteen
Key1: timezone, Value1: 7
Key1: updated_time, Value1: 2015-05-28T04:09:50+0000
Key1: verified, Value1: 1
I wrote a small function for accessing properties in either arrays or objects. I use it quite a bit find it pretty handy
/**
* Access array or object values easily, with default fallback
*/
if( ! function_exists('element') )
{
function element( &$array, $key, $default = NULL )
{
// Check array first
if( is_array($array) )
{
return isset($array[$key]) ? $array[$key] : $default;
}
// Object props
if( ! is_int($key) && is_object($array) )
{
return property_exists($array, $key) ? $array->{$key} : $default;
}
// Invalid type
return NULL;
}
}
function kPrint($key,$obj){
return (gettype($obj)=="array"?(array_key_exists($key,$obj)?$obj[$key]:("<font color='red'>NA</font>")):(gettype($obj)=="object"?(property_exists($obj,$key)?$obj->$key:("<font color='red'>NA</font>")):("<font color='red'><font color='green'>:::Exception Start:::</font><br>Invalid Object/Array Passed at kPrint() Function!!<br> At : Variable => ".print_r($obj)."<br>Key => ".$key."<br> At File: <font color='blue'>".debug_backtrace()[0]['file']."</font><br> At Line : ".debug_backtrace()[0]['line']."<br><font color='green'>:::Exception End:::</font></font>")));}
//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.

Categories