4

I have a small question for you all. I currently have my site on 000webhost, and the following line:

$price  = explode(".",$item->sellingStatus->currentPrice)[0];

causes the following error:

Parse error: syntax error, unexpected '[' in /home/a1257018/public_html/scripts/myfile.php on line 58

When it doesn't cause this on localhost. The code should work... explode returns an array and [0] simply calls the first item. Why is this throwing an error?

hakre
  • 193,403
  • 52
  • 435
  • 836
Nickersoft
  • 684
  • 1
  • 12
  • 30

3 Answers3

10

This syntax is only allowed in PHP 5.4+. You have to use temporary variables in older versions:

$tmp = explode('.', $item->sellingStatus->currentPrice);
$price  = $tmp[0];

Has been discussed on SO.

Community
  • 1
  • 1
just lerning
  • 876
  • 5
  • 20
  • Gah.. that's what I was afraid of. I believe 000webhost uses PHP 5.2. Looks like I have a lot of editing to do. Thanks! – Nickersoft Nov 02 '13 at 18:02
  • 1
    Oh the joy of php ;-) http://me.veekun.com/blog/2012/04/09/php-a-fractal-of-bad-design/ – Sumurai8 Nov 02 '13 at 18:03
  • I still don't know why nobody implemented this earlier. – just lerning Nov 02 '13 at 18:05
  • 3
    Blaming PHP design for this isn't really correct, it's just kicking PHP for the sake of it.... all languages add new features with new versions, using new features of languages like Ruby, Java or C# or any other language against an older version of that language will give errors – Mark Baker Nov 02 '13 at 18:06
  • I don't blame PHP. I just say I don't understand their decision. And I hope Java and C# (not sure about Ruby) implemented array access of return values in their childhood. – just lerning Nov 02 '13 at 18:12
1

Use it as

$array  = explode(".", $item->sellingStatus->currentPrice);
$price = $array[0];

It's because your server doesn't support this syntax because of php < 5.4, here is the same error showing in 5.3.19 and working here using php-5.4.

The Alpha
  • 143,660
  • 29
  • 287
  • 307
0
$price  = explode(".",$item->sellingStatus->currentPrice);
$currentPrice = $price[0];

This should work.

Kush
  • 909
  • 1
  • 8
  • 14