Background
In every other programming language I use on a regular basis, it is simple to operate on the return value of a function without declaring a new variable to hold the function result.
In PHP, however, this does not appear to be so simple:
example1 (function result is an array)
<?php
function foobar(){
return preg_split('/\s+/', 'zero one two three four five');
}
// can php say "zero"?
/// print( foobar()[0] ); /// <-- nope
/// print( &foobar()[0] ); /// <-- nope
/// print( &foobar()->[0] ); /// <-- nope
/// print( "${foobar()}[0]" ); /// <-- nope
?>
example2 (function result is an object)
<?php
function zoobar(){
// NOTE: casting (object) Array() has other problems in PHP
// see e.g., http://stackoverflow.com/questions/1869812
$vout = (object) Array('0'=>'zero','fname'=>'homer','lname'=>'simpson',);
return $vout;
}
// can php say "zero"?
// print zoobar()->0; // <- nope (parse error)
// print zoobar()->{0}; // <- nope
// print zoobar()->{'0'}; // <- nope
// $vtemp = zoobar(); // does using a variable help?
// print $vtemp->{0}; // <- nope
Can anyone suggest how to do this in PHP?
This is specifically array dereferencing, which is currently unsupported in php5.3 but should be possible in the next release, 5.4. Object dereferencing is on the other hand possible in current php releases. I'm also looking forward to this functionality!
my usual workaround is to have a generic function like this
and then
as a bonus, this also avoids 'undefined index' warning when you don't need it.
As to reasons why
foo()[x]
doesn't work, the answer is quite impolite and isn't going to be published here. ;)These are some ways to approach your problem.
First you could use to name variables directly if you return array of variables that are not part of the collection but have separate meaning each.
Other two ways are for returning the result that is a collection of values.
Previously in PHP 5.3 you had to do this:
Result:
2
As of PHP 5.4 it is possible to dereference an array as follows:
Result:
2
As of PHP 5.5:
You can even get clever:
Result:
2
You can also do the same with strings. It's called string dereferencing:
Result:
H