2

Can't wrap my head around this...

Say, we explode the whole thing like so:

$extract = explode('tra-la-la', $big_sourse);

Then we want to get a value at index 1:

$finish = $extract[1];

My question is how to get it in one go, to speak so. Something similar to this:

$finish = explode('tra-la-la', $big_sourse)[1]; // does not work

Something like the following would work like a charm:

$finish = end(explode('tra-la-la', $big_sourse));

// or

$finish = array_shift(explode('tra-la-la', $big_sourse));

But what if the value is sitting somewhere in the middle?

Community
  • 1
  • 1
Alex Polo
  • 905
  • 9
  • 21
  • I don't think that there is a solution, like you are searching for. Why don't you want to store the extracted data into an array before? Why the direct call? Memory-saving-issues? – Fidi Jun 23 '10 at 07:17
  • I just love the solutions with end and array_shift, so I would like something similar to those in case the value is in the middle. But memory could be an issue too, by the way. – Alex Polo Jun 23 '10 at 07:28
  • 2
    possible duplicate of [Access array element from function call in php](http://stackoverflow.com/questions/2282051/access-array-element-from-function-call-in-php) – Gordon Jun 23 '10 at 07:32
  • I don't think this is a dupe, but the link matters. So 'great comment' to you! ;) – Alex Polo Jun 23 '10 at 13:53

4 Answers4

7

Function Array Dereferencing has been implemented in PHP 5.4. For older version that's a limitation in the PHP parser that was fixed in here, so no way around it for now I'm afraid.

kenorb
  • 155,785
  • 88
  • 678
  • 743
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
1

Something like that :

end(array_slice(explode('tra-la-la', $big_sourse), 1, 1));

Though I don't think it's better/clearer/prettier than writing it on two lines.

Serty Oan
  • 1,737
  • 12
  • 19
0

you can use list:

list($first_element) = explode(',', $source);

[1] would actually be the second element in the array, not sure if you really meant that. if so, just add another variable to the list construct (and omit the first if preferred)

list($first_element, $second_elment) = explode(',', $source);
// or
list(, $second_element) = explode(',', $source);
knittl
  • 246,190
  • 53
  • 318
  • 364
0

My suggest - yes, I've figured out something -, would be to use an extra agrument allowed for the function. If it is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string. So, if we want to get, say, a value at index 2 (of course, we're sure that the value we like would be there beforehand), we just do it as follows:

$finish = end(explode('tra-la-la', $big_sourse, 3)); 

explode will return an array that contains a maximum of three elements, so we 'end' to the last element which the one we looked for, indexed 2 - and we're done!

kenorb
  • 155,785
  • 88
  • 678
  • 743
Alex Polo
  • 905
  • 9
  • 21