3

Possible Duplicate:
PHP syntax for dereferencing function result

Here is what I mean. Currently I have to:

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

What I want to do is:

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

But it's a syntax error! Is there another way to do it on one line?

EDIT: Just want to make it clear I also want to be able to do

$str = "foo-bar-baz";
$bar = explode("-",$str)[1];

aswell.

Community
  • 1
  • 1
joedborg
  • 16,427
  • 30
  • 80
  • 114
  • 1
    Array dereferencing is not currently supported in PHP but it will be soon - https://wiki.php.net/rfc/functionarraydereferencing – Phil Sep 16 '11 at 10:19

4 Answers4

6
list($foo) = explode('-', $str);
Maxim Krizhanovsky
  • 25,260
  • 5
  • 51
  • 86
4

Or you can do :

$foo = array_shift(explode("-", $str));

[EDIT] Since the question has changed, now is a very dirty way to do this :

list(,$foo) = explode("-", $str); // Add as many commas as needed to get the proper index
Tom
  • 1,609
  • 11
  • 24
  • 1
    I'm assuming this will only work for first index? – joedborg Sep 16 '11 at 10:28
  • Your question is quite unclear. Now you want to be able to access any index. Plus, you're just trying to find a way to do this in one line instead of two ? – Tom Sep 16 '11 at 10:29
  • Yes, I just want to know if it's possible, I don't believe it is. – joedborg Sep 16 '11 at 10:31
  • 1
    list(,$foo) = explode('-', $str); You can add as many commas to get the index you want. This example will get you [1]. This is one line, but yeah, this is dirty. – Tom Sep 16 '11 at 10:33
0

Another alternative:

$foo = current(explode("-", $str));
Fabio
  • 18,301
  • 9
  • 78
  • 113
  • 1
    I'm assuming this will only work for first index? – joedborg Sep 16 '11 at 10:27
  • Yes, it does work only for the first. It's just an alternative way. However with the [next](http://php.net/manual/en/function.next.php) function you can increment the array internal pointer and use this approach also for other elements. – Fabio Sep 16 '11 at 17:00
0
$foo = explode("-",$str) and $foo = $foo[0];

Seriously, though: There's no shorthand notation for this. You can do it in a few different ways on one line, but none as descriptive and short as the two-line solution you already have.

Emil Vikström
  • 87,715
  • 15
  • 134
  • 170