Page 1 of 1

Left-to-right evaluation?

Posted: Thu Jun 01, 2006 3:28 pm
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.

Posted: Thu Jun 01, 2006 3:33 pm
by PrObLeM
I'm 99.99% sure you can't do it in php.

Posted: Thu Jun 01, 2006 5:12 pm
by Weirdan
in php5 you can.

Posted: Thu Jun 01, 2006 5:16 pm
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.

Posted: Thu Jun 01, 2006 6:15 pm
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

Posted: Thu Jun 01, 2006 6:17 pm
by tomprogers
Right, but I'm talking about things that are not methods, like my explode() example.

Posted: Thu Jun 01, 2006 6:20 pm
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;