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.
7

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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;

Comments

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.

2 Comments

You could use current() without any warning. (Cause that's a language construct, not a function.)
@mario Great! I never used current() function, but now I know that is very useful for that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.