0

Just wondering why this syntax is not working in PHP? What workaround do most people use - if you want to write concise one-liner code?

$str = explode(" ", "foo bar")[0];
// thought $str would be $foo. instead I get error.
// guess I hadn't noticed this issue before.
BuddyJoe
  • 69,735
  • 114
  • 291
  • 466
  • 6
    That's called _array dereferencing_, and it will be available in PHP5.4 (currently in beta). It doesn't work in PHP 5.3 or earlier though. – Michael Berkowski Dec 13 '11 at 21:54
  • 1
    @Michael: I think your comment should be the answer to this question. – Nicolás Ozimica Dec 13 '11 at 21:55
  • 1
    It's buried somewhere in the changelog: http://www.php.net/releases/NEWS_5_4_0_beta2.txt – Michael Berkowski Dec 13 '11 at 21:56
  • 1
    I, for one, can't wait for this feature to arrive and become widely supported as servers get upgraded. – Michael Berkowski Dec 13 '11 at 21:56
  • possible duplicate of [PHP syntax for dereferencing function result](http://stackoverflow.com/questions/742764/php-syntax-for-dereferencing-function-result) or in this particular case [Shortcut for: $foo = explode(“ ”, “bla ble bli”); echo $foo(0)](http://stackoverflow.com/questions/5491885/shortcut-for-foo-explode-bla-ble-bli-echo-foo0) – mario Dec 13 '11 at 21:57
  • @Nicolás Only if I can't find a duplicate. I know it's been asked before. – Michael Berkowski Dec 13 '11 at 21:58
  • @Michael: Last week, I was tempted to install a rogue `php-cgi` in my `/cgi-bin/` just for that very reason. ha – mario Dec 13 '11 at 22:05

3 Answers3

2

PHP is not chainable, meaning you cannot combine the explode function with an accessor, such as [0]. What you want to do is:

$arr = explode(" ", "foo bar");
$str = $arr[0];

"Chainable" may not be the right word, but either way, you can't combine functions like that.

Jon Egeland
  • 12,470
  • 8
  • 47
  • 62
  • 1
    Agreed. Complex one liners are almost always predicated on an unintended behavior of the code. This behavior can change undocumented in a bugfix patch and can even be inconsistent against runtimes. PHP can optimize out whitespace no problem. Optimizing it for a developer to read is much better. – Hasteur Dec 13 '11 at 22:00
2

As people have said, it can't be done like that. If you really, really want to do it in one line, you can use a ternary statement.

$str = ($tmp=explode(" ", "foo bar")) ? $tmp[0] : '';
echo $str; // "foo"

Update:

This can look 'less ugly' if you wrap that into a function.

function single_explode($delim, $str, $index) {
    return ($tmp=explode($delim, $str)) ? $tmp[$index] : '';
}

$str = single_explode(" ", "foo bar", 0);

echo $str;
Brigand
  • 84,529
  • 20
  • 165
  • 173
0

A additional method is use array_shift, that discard the first element of array and return it.

<?php
    echo array_shift(explode(" ", "foo bar")); // === foo
?>

See this full example. Don't use it on strict mode.

David Rodrigues
  • 12,041
  • 16
  • 62
  • 90