php - How can I access an array/object? -
i have following array , when print_r(array_values($get_user));
, 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 access array followed:
echo $get_user[0];
but displays me:
undefined 0
note:
i array facebook sdk 4, don't know original array strucutre.
how can access example value email@saya.com
array?
to access array
or object
how use 2 different operators.
arrays
to access array elements have use either []
or don't see much, can use {}
.
echo $array[0]; echo $array{0}; //both equivalent , interchangeable
difference between declaring array , accessing array element
defining array , accessing array element 2 different things. don't mix them up.
to define array can use array()
or php >=5.4 []
, assign/set array/-element. while when accessing array element []
or {}
mentioned above value of array element opposed setting element.
//declaring array $arraya = array ( /*some stuff in here*/ ); $arrayb = [ /*some stuff in here*/ ]; //only php >=5.4 //accessing array element echo $array[0]; echo $array{0};
access array element
to access particular element in array can use expression inside []
or {}
evaluates key want access:
$array[(any expression)]
so aware of expression use key , how gets interpreted php:
echo $array[0]; //the key integer; accesses 0's element echo $array["0"]; //the key string; accesses 0's element echo $array["string"]; //the key string; accesses element key 'string' echo $array[constant]; //the key constant , gets replaced corresponding value echo $array[constant]; //the key constant , not string echo $array[$anyvariable] //the key variable , gets replaced value in '$anyvariable' echo $array[functionxy()]; //the key return value of function
access multidimensional array
if have multiple arrays in each other have multidimensional array. access array element in sub array have use multiple []
.
echo $array["firstsubarray"]["secondsubarray"]["elementfromthesecondsubarray"] // ├─────────────┘ ├──────────────┘ ├────────────────────────────┘ // │ │ └── 3rd array dimension; // │ └──────────────────── 2d array dimension; // └───────────────────────────────────── 1st array dimension;
objects
to access object property have use ->
.
echo $object->property;
if have object in object have use multiple ->
object property.
echo $objecta->objectb->property;
note:
also have careful if have property name invalid! see problems, can face invalid property name see question/answer. , this one if have numbers @ start of property name.
you can access properties public visibility outside of class. otherwise (private or protected) need method or reflection, can use value of property.
arrays & objects
now if have arrays , objects mixed in each other have if access array element or object property , use corresponding operator it.
//object echo $object->anotherobject->propertyarray["elementonewithanobject"]->property; //├────┘ ├───────────┘ ├───────────┘ ├──────────────────────┘ ├──────┘ //│ │ │ │ └── property ; //│ │ │ └───────────────────────────── array element (object) ; use -> access property 'property' //│ │ └─────────────────────────────────────────── array (property) ; use [] access array element 'elementonewithanobject' //│ └────────────────────────────────────────────────────────── property (object) ; use -> access property 'propertyarray' //└────────────────────────────────────────────────────────────────── object ; use -> access property 'anotherobject' //array echo $array["arrayelement"]["anotherelement"]->object->property["element"]; //├───┘ ├────────────┘ ├──────────────┘ ├────┘ ├──────┘ ├───────┘ //│ │ │ │ │ └── array element ; //│ │ │ │ └─────────── property (array) ; use [] access array element 'element' //│ │ │ └─────────────────── property (object) ; use -> access property 'property' //│ │ └────────────────────────────────────── array element (object) ; use -> access property 'object' //│ └────────────────────────────────────────────────────── array element (array) ; use [] access array element 'anotherelement' //└──────────────────────────────────────────────────────────── array ; use [] access array element 'arrayelement'
i hope gives rough idea how can access arrays , objects, when nested in each other.
note:
if called array or object depends on outermost part of variable.
[new stdclass]
array if has (nested) objects inside of ,$object->property = array();
object if has (nested) arrays inside.and if not sure if have object or array, use
gettype()
.
don't confused if uses coding style you:
//both methods/styles work , access same data echo $object->anotherobject->propertyarray["elementonewithanobject"]->property; echo $object-> anotherobject ->propertyarray ["elementonewithanobject"]-> property; //both methods/styles work , access same data echo $array["arrayelement"]["anotherelement"]->object->property["element"]; echo $array["arrayelement"] ["anotherelement"]-> object ->property["element"];
arrays, objects , loops
if don't want access single element can loop on nested array / object , go through values of particular dimension.
for have access dimension on want loop , can loop on values of dimension.
as example take array, object:
array ( [data] => array ( [0] => stdclass object ( [propertyxy] => 1 ) [1] => stdclass object ( [propertyxy] => 2 ) [2] => stdclass object ( [propertyxy] => 3 ) ) )
if loop on first dimension values first dimension:
foreach($array $key => $value)
means here in first dimension have 1 element key($key
) data
, value($value
):
array ( //key: array [0] => stdclass object ( [propertyxy] => 1 ) [1] => stdclass object ( [propertyxy] => 2 ) [2] => stdclass object ( [propertyxy] => 3 ) )
if loop on second dimension values second dimension:
foreach($array["data"] $key => $value)
means here in second dimension have 3 element keys($key
) 0
, 1
, 2
, values($value
):
stdclass object ( //key: 0 [propertyxy] => 1 ) stdclass object ( //key: 1 [propertyxy] => 2 ) stdclass object ( //key: 2 [propertyxy] => 3 )
and can loop through dimension want no matter if array or object.
analyse var_dump()
/ print_r()
/ var_export()
output
all of these 3 debug functions output same data, in format or meta data (e.g. type, size). here want show how have read output of these functions know/get way how access data 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' => stdclass::__set_state(array( 'property' => array ( 0 => 1, 1 => 2, 2 => 3, ), )), )
so can see outputs pretty similar. , if want access value 2 can start value itself, want access , work way out "top left".
1. first see, value 2 in array key 1
array(3) { //var_dump() [0]=> int(1) [1]=> int(2) [2]=> int(3) }
array //print_r() ( [0] => 1 [1] => 2 [2] => 3 )
array ( //var_export() 0 => 1, 1 => 2, 2 => 3, ),
this means have use []
/{}
access value 2 [1]
, since value has key/index 1.
2. next see, array assigned property name property of object
object(stdclass)#1 (1) { //var_dump() ["property"]=> /* array here */ }
stdclass object //print_r() ( [property] => /* array here */ )
stdclass::__set_state(array( //var_export() 'property' => /* array here */ )),
this means have use ->
access property of object, e.g. ->property
.
so until know, have use ->property[1]
.
3. , @ end see, outermost array
array(1) { //var_dump() ["key"]=> /* object & array here */ }
array //print_r() ( [key] => /* object & array here */ )
array ( //var_export() 'key' => /* object & array here */ )
as know have access array element []
, see here have use ["key"]
access object. can put these parts , write:
echo $array["key"]->property[1];
and output be:
2
don't let php troll you!
there few things, have know, don't spend hours on finding them.
"hidden" characters
sometimes have characters in keys, don't see on first in browser. , you're asking yourself, why can't access element. these characters can be: tabs (
\t
), new lines (\n
), spaces or html tags (e.g.</p>
,<b>
), etc.as example if @ output of
print_r()
, see:array ( [key] => here )
then trying access element with:
echo $arr["key"];
but getting notice:
notice: undefined index: key
this indication there must hidden characters, since can't access element, if keys seems pretty correct.
the trick here use
var_dump()
+ source code! (alternative:highlight_string(print_r($variable, true));
)and of sudden maybe see stuff this:
array(1) { ["</b> key"]=> string(4) "here" }
now see, key has html tag in + new line character, didn't saw in first place, since
print_r()
, browser didn't showed that.so if try do:
echo $arr["</b>\nkey"];
you desired output:
here
never trust output of
print_r()
orvar_dump()
if @ xmlyou might have xml file or string loaded object, e.g.
<?xml version="1.0" encoding="utf-8" ?> <rss> <item> <title attribute="xy" ab="xy">test</title> </item> </rss>
now if use
var_dump()
orprint_r()
see:simplexmlelement object ( [item] => simplexmlelement object ( [title] => test ) )
so can see don't see attributes of title. said never trust output of
var_dump()
orprint_r()
when have xml object. useasxml()
see full xml file/string.so use 1 of methods shown below:
echo $xml->asxml(); //and source code highlight_string($xml->asxml()); header ("content-type:text/xml"); echo $xml->asxml();
and 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 - symbol mean in php?
- reference - error mean in php?
- php parse/syntax errors; , how solve them?
property name problems