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
  • 67,353
  • 112
  • 287
  • 456

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,064
  • 8
  • 46
  • 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
  • 80,366
  • 19
  • 159
  • 169
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
  • 11,320
  • 14
  • 53
  • 87