tags:

views:

69

answers:

4

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?

+7  A: 

That's a limitation in the PHP parser that was fixed only recently. No way around it for now I'm afraid.

Ignacio Vazquez-Abrams
Dereferencing arrays from function calls was fixed recently? When?
Gordon
@gordon: See added link.
Ignacio Vazquez-Abrams
I wasn't aware that it had been fixed! Do you have a link to where this fix was announced?
too much php
This is not in an official release yet though, is it?
Pekka
Nope. Hence the "for now".
Ignacio Vazquez-Abrams
@Ignacio you really made my day with that news
Gordon
Wow... that will change my whole PHP experience! Not sure if I am ready for such a change ;)
Felix Kling
+1  A: 

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
A: 

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
It's all fun and games until someone tries to get the `n`th element.
Ignacio Vazquez-Abrams
@ignacio: well, then it's best to save the array, do bound checks and then retrieve the value. you can always write another function for that ;)
knittl
A: 

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!

Alex Polo