PHP - extracting array values ​​(square brackets and arrow designation)

I have an object, and when I am a var_dump user, I get the following:

 var_dump($object); array (size=7) 'id' => int 1969 'alt' => string '' (length=0) 'title' => string 'File Name' (length=9) 'url' => string 'http://location/file.pdf' (length=24) 

When I echo $object[url] , it returns string 'http://location/file.pdf' (length=24) , however, when I echo $object->url , I get null . (This sometimes works to extract values ​​from an array, I'm just not sure in what cases or in what types of arrays)

The problem is that I am using a hosting provider with the git function, and when I push my changes, it checks the PHP code and detects a syntax error (unexpected "[") that stops the click.

My local server uses PHP 5.4.16 and the host uses 5.3.2

In a wider note, can someone point me to a resource that explains the difference between the two methods of extracting values ​​from arrays? Really appreciate!

+5
source share
2 answers

You have no object, you have an associative array. Note the very first word in your var_dump() output:

 array 

So $object->url doesn't make sense and actually gives you a message about trying to access a non-object property.

I could not imagine any process for checking the syntax associated with PHP that would bring an error to something like $foo['bar'] . Whether it is an object or an array, as a rule, cannot be determined by a simple syntax check. You may have other typos that precede this.

+7
source

You cannot access arrays as follows: -> , which applies only to objects like the following:

 $x = (object) array('a'=>'A', 'b'=>'B', 'C'); gives you: stdClass Object ( [a] => A [b] => B [0] => C ) 

To access these values, you must do this with -> as follows:

 $valA = $x->a; 
+4
source

Source: https://habr.com/ru/post/1203944/


All Articles