Left-to-right evaluation?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
tomprogers
Forum Commoner
Posts: 50
Joined: Fri Mar 17, 2006 5:17 pm
Location: Minnesota
Contact:

Left-to-right evaluation?

Post by tomprogers »

If I'm interested in, say, the third element of a function's return array, I'd do this:

Code: Select all

$third = explode(' ', 'blah blah blah');
print( $third[2] );
If I'm only interested in one of the elements of the array, some languages let me do this:

Code: Select all

print( explode(' ', 'blah blah blah')[2] );
I know JavaScript lets you do all kinds of crazy stuff:

Code: Select all

alert(oForm.elements[i].toFloat(3).toString().toUpper()); // not super useful, but it's the right idea
I can't get PHP to do the same thing. Is this because PHP doesn't support that kind of... "immediate evaluation," or am I simply not using the proper syntax? I've tried wrapping the function call in parentheses (a la ternary operation) and curly braces, but no success.

Also, if someone know the proper term for the functionality I'm talking about, I'd appreciate them mentioning it. I ran across it once several years ago, but I have since forgotten it and don't know where I found it.
User avatar
PrObLeM
Forum Contributor
Posts: 418
Joined: Sun Mar 07, 2004 2:30 pm
Location: Mesa, AZ
Contact:

Post by PrObLeM »

I'm 99.99% sure you can't do it in php.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

in php5 you can.
tomprogers
Forum Commoner
Posts: 50
Joined: Fri Mar 17, 2006 5:17 pm
Location: Minnesota
Contact:

Post by tomprogers »

I ran the following code:

Code: Select all

print( explode(' ', 'blah blah blah')[2] );
And got the following error:
Parse error: parse error, unexpected '[' in /test.php on line 1
phpinfo() shows that I'm running PHP 5.0.5.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

It was ment the following would work in PHP5:

Code: Select all

$object->property->method()->property;
It's similar to your last example
tomprogers
Forum Commoner
Posts: 50
Joined: Fri Mar 17, 2006 5:17 pm
Location: Minnesota
Contact:

Post by tomprogers »

Right, but I'm talking about things that are not methods, like my explode() example.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

I'm afraid the best you can do with php is:

Code: Select all

list(,$second,) = explode(" ", "blah second-blah third-blah");
echo $second;
Post Reply