To access an array
or object
you how to use two different operators.
To access array elements you have to use either []
or which you don't see that much, but which you can also use is {}
.
echo $array[0];
echo $array{0};
//Both are equivalent and interchangeable
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 []
or {}
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];
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;
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.
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' =>
stdClass::__set_state(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
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,
),
<