error in getting values from array stdClass php

Posted on

Question :

When I use echo var_dump($location); I get this:

object(stdClass)#1226 (2) { ["type"]=> string(5) "Point" ["coordinates"]=> array(2) { [0]=> float(44.0928438) [1]=> float(-70.20876942) } }

I tried to get the floats (44.0928438, -70.20876942), with the following code:

$lat = $location["type"]["coordinates"][0];
$long = $location["type"]["coordinates"][1];

But when I run my php file, it gives me the following error not because:


Fatal error: Can not use object of type stdClass as array in
  online 62


Answer :

It happens that the syntax of brackets until a certain time ago was an exclusivity of the arrays.

However, little by little (relatively speaking) the objects were being improved. First they could be iterated just like a normal array. The natural consequence of this would be for objects that represent an array to also be able to adopt bracket syntax.

This ability is for making an object implement the ArrayAccess interface (and its methods). Ironically, it looks like the stdClass class did not receive this implementation, so the Fatal Error .

To solve the problem you have two options:

  • Map this stdClass object to an array:

    function map( $param ) {
        if( is_object( $param ) ) {
            $param = get_object_vars( $param );
        if( is_array( $param ) ) {
            return array_map( __FUNCTION__, $param );
        return $param;

    You can also force the cast of this object to array:

    $data = (array) $original;

    But this is not recursive. In your case it would not be a problem since you have a single stdClass object, but the above function it’s worth as a reference because it converts to array as many stdClass as many as it finds, hierarchically speaking.

  • Look for alternatives to the do not come result in a stdClass

    Because of the contents of the entries of this object, it is notable that there is a consumption of a GeoTargeting API or at least a fetching of database data using objects such as fetching style

    In the case of an API, the data is usually transported in JSON which is a “universal” format. To work with JSON with PHP you use json_decode () with intent to produce an array.

    For PHP, your intentions are almost always worthless. That’s why, by default, json_decode () returns the data in stdClass .

    However, it is simple to get around this. Just pass the second json_decode () argument as TRUE :

    $data = jsondecode( $original, TRUE );

    If the data is influenced by a fetching style check the documentation of how you read the query feature by setting no objects to be used.

    For PDO , for example, a resource is returned in both indexed and associative arrays (PDO::FETCH_BOTH ), but it is quite common to be changed to PDO :: FETCH_ASSOC or, in the case that may be yours, PDO :: FETCH_OBJ

  • Leave a Reply

    Your email address will not be published. Required fields are marked *