0

I've seen people write code like this:

$image_url =  wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), array(300, 300), false, ''); 
$image_url = $image_url[0];

which seems a little ridiculous because you could just attach the [0] to the end of the first term. So I never did it in my local machine, but now when deploying to remote machines (with possibly different versions of php, I always get bugs about unexpected '['. Does php not accept accessing arrays in-place, or was there some change in some version?

Shikiryu
  • 10,070
  • 7
  • 48
  • 74
Xiv
  • 7,144
  • 2
  • 26
  • 29
  • I believe it's just a bad practice. Semantics over "saving 14 characters" – Ofir Baruch Aug 04 '13 at 18:57
  • You could also do `array_shift(...);` to get the zero-index. A simpler example could be: `$fileExt = array_pop(explode('.', $filename));` (`array_pop()` simply is the inverse of `array_shift()`). – Jared Farrish Aug 04 '13 at 18:58
  • and [Getting element from PHP array returned by function](http://stackoverflow.com/q/8888591) – mario Aug 04 '13 at 19:00

3 Answers3

4

This is allowed since PHP 5.4:

Function array dereferencing has been added, e.g. foo()[0].

moonwave99
  • 20,750
  • 2
  • 41
  • 64
1

Which version of PHP are you using? Function array dereferencing is allowed in PHP 5.4 (and above).

Patt Mehta
  • 4,034
  • 1
  • 21
  • 45
1

In PHP < 5.4, you can't take an element from an array before it exists... You must come from a Python or Ruby world where this kind of syntax is allowed.

If you have PHP < 5.4, you have to set the array and after get the index you want.

Maxime Lorant
  • 31,821
  • 17
  • 84
  • 96