Zink Zink - 4 months ago 19
PHP Question

How to access array within PHP object

I know this question is a little n00b but I am struggling to work out to how to access the array 'ta[]' within the PHP object below. Usually I would have no problem but because my key contains the brackets i.e. 'ta[]' I can't wrap my head around how to access it, I guess I somehow need to escape it..?

I have tried most combinations such as..

object->ta[]
object["ta[0]"]
object["ta[]"]
object->ta[0]


Any help welcome!

object(stdClass)#6 (11) {
["tc"]=> string(4) "4500"
["tct"]=> string(1) "1"
["pd"]=> string(2) "AT"
["df"]=> string(10) "08/04/2016"
["dt"]=> string(10) "08/08/2016"
["nt"]=> string(1) "2"
["ta[]"]=> array(2)
{
[0]=> string(2) "40"
[1]=> string(2) "35"
}
["rc"]=> string(2) "US"
["rs"]=> string(2) "AR"
["cc"]=> string(2) "US"
["dfp"]=> string(10) "07/30/2016"
}

Answer

This should do it

$obj->{"ta[]"};

Brace notation (using {}) does the same thing for accessing object properties as bracket notation (using []) does for accessing array keys: It lets you define the property name as an expression.

Which in this case is just a simple string but could could be any other expression. To prove that with a (silly) example:

function ta() {
    return 'ta';
}

$obj = new stdClass;
$obj->{ta() . '[]'} = ['a', 'b'];
echo $obj->{"ta[]"}[1]; // b
Comments