Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - extracting array values ( square brackets vs arrow notation )

Tags:

arrays

php

I have an object and when I user var_dump 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 for extracting values from an array, I'm just not sure in which cases or what type of arrays)

The problem is that I use a hosting provider that has a git feature, and when I push my changes, it checks the PHP code and encounters a syntax error (unexpected '[') which halts the push.

My local server uses PHP 5.4.16 and the host uses 5.3.2

On a broader note, can someone point me to a resource that explains the difference between these two methods of extracting values from arrays? Much appreciated!

like image 670
psorensen Avatar asked Oct 03 '14 14:10

psorensen


1 Answers

You can't access arrays this way : -> that only applies 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 have to do it the way with -> like so:

$valA = $x->a;
like image 75
Daan Avatar answered Sep 18 '22 20:09

Daan