Related
I prefer to program in Python language, but have to work in PHP for a specific web site app project.
In PHP I am trying to "return" a value from a function to the main program environment (to be used for subsequent calculations), but no matter what I try the value calculated in my function is not returning the value (but echoing from function works fine).
In Python I never had an issue with returning variables: i.e. all values returned from functions were available and accessible to the main program and/or other functions that called the function that produces the return value.
Can someone please tell me how I can solve this issue? I have been searching google and sites ike stackoverflow for the last 2 days with no success. I have many O'Reilly computer books including many on PHP where I have cross referenced my research and read everything I can about the RETURN function - it seems I am doing everything right and even specifically declaring the value to be returned. It is critical that I am able to return values and have access to those values in order to proceed with development on this project - else I am stuck if I cannot return values to be processed further!!
Here is the relevant code pieces:
// DECLARE FUNCTIONS
// FUNCTION
function Calculation_IsArray ($ArrayAny){
if (is_array($ArrayAny)) {
echo '<div>THIS VAR IS AN ARRAY</div>';
$Var_IsArray = TRUE;
return $Var_IsArray;
} else {
echo '<div>THIS VAR IS **NOT** AN ARRAY</div>';
}
}
After declaring the functions and doing some initial calculations to grab an array for checking, I call the above function as follows:
// CALL FUNCTION
Calculation_IsArray($ArrayOfValues);
I am expecting the program to call the function Calculation_IsArray() and pass it the array to be checked ($ArrayOfValues). You can see from the output below that the array is passed and checked and confirmed to be of array type, and both the FOREACH loop as well as the IF/ELSE conditions are working fine and echoing the correct output. However, the above code does not return any values as you can see the NULL values that are echoed when I check for returned values (i.e. that array that was checked) accessible from the main program after the "return".
And here are the results echoed to browser screen (output):
THIS VAR IS AN ARRAY
RETURNED ARRAY =
NULL
VALUE OF $Var_IsArray =
NULL
COUNT OF ARRAY KEY ELEMENTS = 2
ARRAY KEY ELEMENTS ARE NUMERIC
KEY = 0, VALUE = Array
COUNT OF ARRAY KEY ELEMENTS = 2
ARRAY KEY ELEMENTS ARE NUMERIC
KEY = 1, VALUE = Array
I have searched here at stackoverflow and found reports of similar problems (and I even tried to test those suggestions for solutions, e.g. placing return at various places in my function to test where it would work), but nothing is working, and this failure to return value is not logical according to what I have read that PHP returns values if expliciting told to RETURN.
Thank you very much for any help in this matter!
[After submission of the original question above]:
I am now trying to isolate my problem by creating a test script called TestReturn.php.
In that script I have placed the following code, but still there is no value returned!!
// DECLARE FUNCTIONS
// FUNCTION
function Calculation_IsArray ($ArrayAny){
if (is_array($ArrayAny)) {
echo '<div>THIS VAR IS AN ARRAY</div>';
$Var_IsArray = TRUE;
return $Var_IsArray;
} else {
echo '<div>THIS VAR IS **NOT** AN ARRAY</div>';
}
}
// BEGIN MAIN PROGRAM
$x = array(1, 2, 3, 4, 5, 6, 7);
Calculation_IsArray($x);
// COME BACK TO HERE AFTER THE FUNCTION RETURNS CALCULATED VALUE
echo '<div>HERE IS THE RETURNED VALUE AND VAR_DUMP BELOW:' . $Var_IsArray . '</div>';
var_dump($Var_IsArray);
And here is the output in HTML to browser tab/window/terminal:
THIS VAR IS AN ARRAY
HERE IS THE RETURNED VALUE AND VAR_DUMP BELOW:
NULL
"Captain, this does not compute!", i.e. this doesn't make sense to me why PHP is not returning my value that I specifically tell it to return to main program!
I have tried all possibilities of coding including:
return $variable;
return ($variable);
return() ; // i.e. I read somewhere that PHP by default returns the last calculated value in a function.
return ;
Why is PHP not returning my value/variable back to main program?
When you return something from a function, it doesn't make the variable itself available in the calling scope (i.e. outside the function). In other words, $Var_IsArray only exists inside the function.
Only the contents of the variable are returned, and you must use the result immediately where you call the function; e.g. store it for future reference, pass it to another function, or test it in a condition.
For example:
function foo()
{
$vals = ['red', 'green', 'blue'];
return $vals;
}
$somedata = foo();
In this example, $somedata will end up holding the array that previously was stored in $vals.
This is the standard behaviour for return statements (or equivalent functionality) in most programming languages. There are other ways to get variables out of a function, e.g. by using global variables. Generally, they're not good practice though.
I've used Python before too, and I don't think it's any different (unless I've missed a major language feature). You might want to double-check that your Python code is doing what you think it's doing, otherwise you could end up with some nasty bugs in future.
you could simplify the function to the following so it always returns something ( true,false )
function Calculation_IsArray( $ArrayAny ){
echo is_array($ArrayAny) ? '<div>THIS VAR IS AN ARRAY</div>' : '<div>THIS VAR IS **NOT** AN ARRAY</div>';
return is_array($ArrayAny);
}
Hope this will help:
// FUNCTION
function Calculation_IsArray ($ArrayAny){
if (is_array($ArrayAny)) {
echo '<div>THIS VAR IS AN ARRAY</div>';
return true;
} else {
echo '<div>THIS VAR IS **NOT** AN ARRAY</div>';
return false;
}
}
$array = array(1, 1, 1);
if ( Calculation_IsArray($array) ){
print_r( $array );
}
<?php
// DECLARE FUNCTIONS
// FUNCTION
function Calculation_IsArray ($ArrayAny){
if (is_array($ArrayAny)) {
echo '<div>THIS VAR IS AN ARRAY</div>';
//$Var_IsArray = TRUE;
return true;
} else {
echo '<div>THIS VAR IS **NOT** AN ARRAY</div>';
}
}
// BEGIN MAIN PROGRAM
$x = array(1, 2, 3, 4, 5, 6, 7);
$status = Calculation_IsArray($x);
if($status == true){
// COME BACK TO HERE AFTER THE FUNCTION RETURNS CALCULATED VALUE
echo '<div>HERE IS THE RETURNED VALUE AND VAR_DUMP BELOW:<br />' . print_r($x) . '</div>';
var_dump($x);
}
ok, so while Peter Bloomfield was responding and writing his CORRECT answer, I was hacking away myself and trying different things and remembered that what I also do in Python is make a variable equal to the function call!! I tried that and now it is returning fine anything I do with that function, thank GOD!!
Here is the updated code in main program now that received ok the returned value (it is no longer returning just NULL):
// BEGIN MAIN PROGRAM
$x = array(1, 2, 3, 4, 5, 6, 7);
$ResultOfCalculation = Calculation_IsArray($x);
// COME BACK TO HERE AFTER THE FUNCTION RETURNS CALCULATED VALUE
echo '<div>HERE IS THE RETURNED VALUE AND VAR_DUMP BELOW:' . $ResultOfCalculation . '</div>';
var_dump($ResultOfCalculation);
The main function of the example class uses the reusableFunction twice with different data and attempts to send that data to a different instance variable ($this->result1container and $this->result2container) in each case, but the data doesn't get into the instance variables.
I could get it to work by making reusableFunction into two different functions, one with array_push($this->result1container, $resultdata) and the other with array_push($this->result2container, $resultdata), but I am trying to find a solution that doesn't require me to duplicate the code.
My solution was to try to pass the name of the result container into the function, but no go. Does somebody know a way I could get this to work?
Example Code:
Class Example {
private $result1container = array();
private $result2container = array();
function __construct() {
;
}
function main($data1, $data2) {
$this->reusableFunction($data1, $this->result1container);
$this->reusableFunction($data2, $this->result2container);
}
function reusableFunction($data, $resultcontainer) {
$resultdata = $data + 17;
// PROBLEM HERE - $resultcontainer is apparently not equal to
// $this->result1container or $this->result2container when I
// try to pass them in through the parameter.
array_push($resultcontainer, $resultdata);
}
function getResults() {
return array(
"Container 1" => $this->result1container,
"Container 2" => $this->result2container);
}
}
(If this is a duplicate of a question, I apologize and will happily learn the answer from that question if somebody would be kind enough to point me there. My research didn't turn up any answers, but this might just be because I didn't know the right question to be searching for)
It looks to me like you want to be passing by reference:
function reusableFunction($data, &$resultcontainer) {
...
If you don't pass by reference with the & then you are just making a local copy of the variable inside reuseableFunction .
You are changing the copy, not the original. Alias the original Array by referenceDocs:
function reusableFunction($data, &$resultcontainer) {
# ^
And that should do the job. Alternatively, return the changed Array and assign it to the object member it belongs to (as for re-useability and to keep things apart if the real functionality is doing merely the push only).
Additionally
array_push($resultcontainer, $resultdata);
can be written as
$resultcontainer[] = $resultdata;
But that's just really FYI.
You may pass the attributes name as a String to the method like this:
function reusableFunction($data, $resultcontainer) {
$resultdata = $data + 17;
array_push($this->{$resultcontainer}, $resultdata);
}
//..somewhere else..
$this->reusableFunction($data, 'result2Container')
Some php experts wrote some texts about "why you shouldn't use byReference in php".
Another solution would be to define the containers as an array. Then you can pass an "key" to the method that is used to store the result in the array. Like this:
private $results = array();
function reusableFunction($data, $resIdx) {
$resultdata = $data + 17;
array_push($this->$results[$resIdx], $resultdata);
}
//..somewhere else..
$this->reusableFunction($data, 'result2Container');
//..or pass a number as index..
$this->reusableFunction($data, 1);
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
PHP can not access array results from a function. Some people call this an issue, some just accept this as how the language is designed. So PHP makes you create unessential variables just to extract the data you need.
So you need to do.
$var = foobar();
print($var[0]);
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!
Array Dereferencing is possible as of PHP 5.4:
http://svn.php.net/viewvc?view=revision&revision=300266
Example (source):
function foo() {
return array(1, 2, 3);
}
echo foo()[2]; // prints 3
with PHP 5.3 you'd get
Parse error: syntax error, unexpected '[', expecting ',' or ';'
Original Answer:
This has been been asked already before. The answer is no. It is not possible.
To quote Andi Gutmans on this topic:
This is a well known feature request
but won't be supported in PHP 5.0. I
can't tell you if it'll ever be
supported. It requires some research
and a lot of thought.
You can also find this request a number of times in the PHP Bugtracker. For technical details, I suggest you check the official RFC and/or ask on PHP Internals.
Well, you could use any of the following solutions, depending on the situation:
function foo() {
return array("foo","bar","foobar","barfoo","tofu");
}
echo(array_shift(foo())); // prints "foo"
echo(array_pop(foo())); // prints "tofu"
Or you can grab specific values from the returned array using list():
list($foo, $bar) = foo();
echo($foo); // prints "foo"
echo($bar); // print "bar"
Edit: the example code for each() I gave earlier was incorrect. each() returns a key-value pair. So it might be easier to use foreach():
foreach(foo() as $key=>$val) {
echo($val);
}
There isn't a way to do that unfortunately, although it is in most other programming languages.
If you really wanted to do a one liner, you could make a function called a() and do something like
$test = a(func(), 1); // second parameter is the key.
But other than that, func()[1] is not supported in PHP.
As others have mentioned, this isn't possible. PHP's syntax doesn't allow it. However, I do have one suggestion that attacks the problem from the other direction.
If you're in control of the getBarArray method and have access to the PHP Standard Library (installed on many PHP 5.2.X hosts and installed by default with PHP 5.3) you should consider returning an ArrayObject instead of a native PHP array/collection. ArrayObjects have an offetGet method, which can be used to retrieve any index, so your code might look something like
<?php
class Example {
function getBarArray() {
$array = new ArrayObject();
$array[] = 'uno';
$array->append('dos');
$array->append('tres');
return $array;
}
}
$foo = new Example();
$value = $foo->getBarArray()->offsetGet(2);
And if you ever need a native array/collection, you can always cast the results.
//if you need
$array = (array) $foo->getBarArray();
Write a wrapper function that will accomplish the same. Because of PHP's easy type-casting this can be pretty open-ended:
function array_value ($array, $key) {
return $array[$key];
}
If you just want to return the first item in the array, use the current() function.
return current($foo->getBarArray());
http://php.net/manual/en/function.current.php
Actually, I've written a library which allows such behavior:
http://code.google.com/p/php-preparser/
Works with everything: functions, methods. Caches, so being as fast as PHP itself :)
You can't chain expressions like that in PHP, so you'll have to save the result of array_test() in a variable.
Try this:
function array_test() {
return array(0, 1, 2);
}
$array = array_test();
echo $array[0];
This is too far-fetched, but if you really NEED it to be in one line:
return index0( $foo->getBarArray() );
/* ... */
function index0( $some_array )
{
return $some_array[0];
}
You could, of course, return an object instead of an array and access it this way:
echo "This should be 2: " . test()->b ."\n";
But I didn't find a possibility to do this with an array :(
my usual workaround is to have a generic function like this
function e($a, $key, $def = null) { return isset($a[$key]) ? $a[$key] : $def; }
and then
echo e(someFunc(), 'key');
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.
function test() {
return array(1, 2);
}
list($a, $b) = test();
echo "This should be 2: $b\n";
function test2() {
return new ArrayObject(array('a' => 1, 'b' => 2), ArrayObject::ARRAY_AS_PROPS);
}
$tmp2 = test2();
echo "This should be 2: $tmp2->b\n";
function test3() {
return (object) array('a' => 1, 'b' => 2);
}
$tmp3 = test3();
echo "This should be 2: $tmp3->b\n";
Extremely ghetto, but, it can be done using only PHP. This utilizes a lambda function (which were introduced in PHP 5.3). See and be amazed (and, ahem, terrified):
function foo() {
return array(
'bar' => 'baz',
'foo' => 'bar',
}
// prints 'baz'
echo call_user_func_array(function($a,$k) {
return $a[$k];
}, array(foo(),'bar'));
The lengths we have to go through to do something so beautiful in most other languages.
For the record, I do something similar to what Nolte does. Sorry if I made anyone's eyes bleed.
After further research I believe the answer is no, a temporary variable like that is indeed the canonical way to deal with an array returned from a function.
Looks like this will change starting in PHP 5.4.
Also, this answer was originally for this version of the question:
How to avoid temporary variables in PHP when using an array returned from a function
Previously in PHP 5.3 you had to do this:
function returnArray() {
return array(1, 2, 3);
}
$tmp = returnArray();
$ssecondElement = $tmp[1];
Result: 2
As of PHP 5.4 it is possible to dereference an array as follows:
function returnArray() {
return array(1, 2, 3);
}
$secondElement = returnArray()[1];
Result: 2
As of PHP 5.5:
You can even get clever:
echo [1, 2, 3][1];
Result: 2
You can also do the same with strings. It's called string dereferencing:
echo 'PHP'[1];
Result: H
If it is just aesthetic, then the Object notation will work if you return an object. As far as memory management goes, no temporary copy if made, only a change in reference.
Short Answer:
Yes. It is possible to operate on the return value of a function in PHP, so long as the function result and your particular version of PHP support it.
Referencing example2:
// can php say "homer"?
// print zoobar()->fname; // homer <-- yup
Cases:
The function result is an array and your PHP version is recent enough
The function result is an object and the object member you want is reachable
There are three ways to do the same thing:
As Chacha102 says, use a function to return the index value:
function get($from, $id){
return $from[$id];
}
Then, you can use:
get($foo->getBarArray(),0);
to obtain the first element and so on.
A lazy way using current and array_slice:
$first = current(array_slice($foo->getBarArray(),0,1));
$second = current(array_slice($foo->getBarArray(),1,1));
Using the same function to return both, the array and the value:
class FooClass {
function getBarArray($id = NULL) {
$array = array();
// Do something to get $array contents
if(is_null($id))
return $array;
else
return $array[$id];
}
}
Then you can obtain the entire array and a single array item.
$array = $foo->getBarArray();
or
$first_item = $foo->getBarArray(0);
Does this work?
return ($foo->getBarArray())[0];
Otherwise, can you post the getBarArray() function? I don't see why that wouldn't work from what you posted so far.
You could use references:
$ref =& myFunc();
echo $ref['foo'];
That way, you're not really creating a duplicate of the returned array.
I'm sorry for asking this question, but I'm not good in php (beginner).
Could you please explain what $arg means in this piece of code? (it's from one of drupal modules)
function node_add_review_load($arg) {
global $user;
$add_review = FALSE;
$current_node = node_load($arg);
$type =$current_node->type;
$axes_count = db_result(db_query("SELECT COUNT(*) FROM {nodereview_axes} WHERE node_type='%s'", $type));
if (variable_get('nodereview_use_' . $type, 0) && $axes_count) {
$add_review = db_result(db_query("SELECT n.nid FROM {node} n INNER JOIN {nodereview} nr ON n.nid=nr.nid WHERE uid=%d AND reviewed_nid=%d", $user->uid, $arg));
}
return $add_review ? FALSE : $arg;
}
Thank you.
http://nl.php.net/manual/en/functions.arguments.php
When a programmer uses node_add_review_load() he can pass the argument which can be used in the function.
The function returns another value if the argument $arg is different.
So the programmer can do this:
node_add_review_load("my argument");
//and the php automatically does:
$arg = "my argument";
//before executing the rest of the function.
In general, arg is short for "argument," as in "an argument to a function." It's a generic, and thus unhelpful, name. If you'd just given the method signature (function node_add_review_load($arg)) we'd have no idea.
Fortunately, with the complete function body, we can deduce its purpose: it is the node_id. This function loads the node identified by $arg and then tries to find a corresponding row that's loaded, and that the code then tries to find a corresponding review for the current user. If successful, the function will return that same node_id (i.e., $arg); otherwise it will return FALSE.
It's an argument.
Example,
// function
function sum($arg1, $arg2)
{
return $arg1+$arg2;
}
// prints 4
echo sum(2,2);
You don't have to call it $arg for it to be valid. For example,
function sum($sillyWilly, $foxyFox)
{
return $sillyWilly+$foxyFox;
}
And it would work the same. You should give arguments useful names. In this case, the argument $arg is bad programming practice because someone like you would look at it and get confused by what it means exactly. So in cases where you make functions, be sure to use useful names so you'll remember.
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
PHP can not access array results from a function. Some people call this an issue, some just accept this as how the language is designed. So PHP makes you create unessential variables just to extract the data you need.
So you need to do.
$var = foobar();
print($var[0]);
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!
Array Dereferencing is possible as of PHP 5.4:
http://svn.php.net/viewvc?view=revision&revision=300266
Example (source):
function foo() {
return array(1, 2, 3);
}
echo foo()[2]; // prints 3
with PHP 5.3 you'd get
Parse error: syntax error, unexpected '[', expecting ',' or ';'
Original Answer:
This has been been asked already before. The answer is no. It is not possible.
To quote Andi Gutmans on this topic:
This is a well known feature request
but won't be supported in PHP 5.0. I
can't tell you if it'll ever be
supported. It requires some research
and a lot of thought.
You can also find this request a number of times in the PHP Bugtracker. For technical details, I suggest you check the official RFC and/or ask on PHP Internals.
Well, you could use any of the following solutions, depending on the situation:
function foo() {
return array("foo","bar","foobar","barfoo","tofu");
}
echo(array_shift(foo())); // prints "foo"
echo(array_pop(foo())); // prints "tofu"
Or you can grab specific values from the returned array using list():
list($foo, $bar) = foo();
echo($foo); // prints "foo"
echo($bar); // print "bar"
Edit: the example code for each() I gave earlier was incorrect. each() returns a key-value pair. So it might be easier to use foreach():
foreach(foo() as $key=>$val) {
echo($val);
}
There isn't a way to do that unfortunately, although it is in most other programming languages.
If you really wanted to do a one liner, you could make a function called a() and do something like
$test = a(func(), 1); // second parameter is the key.
But other than that, func()[1] is not supported in PHP.
As others have mentioned, this isn't possible. PHP's syntax doesn't allow it. However, I do have one suggestion that attacks the problem from the other direction.
If you're in control of the getBarArray method and have access to the PHP Standard Library (installed on many PHP 5.2.X hosts and installed by default with PHP 5.3) you should consider returning an ArrayObject instead of a native PHP array/collection. ArrayObjects have an offetGet method, which can be used to retrieve any index, so your code might look something like
<?php
class Example {
function getBarArray() {
$array = new ArrayObject();
$array[] = 'uno';
$array->append('dos');
$array->append('tres');
return $array;
}
}
$foo = new Example();
$value = $foo->getBarArray()->offsetGet(2);
And if you ever need a native array/collection, you can always cast the results.
//if you need
$array = (array) $foo->getBarArray();
Write a wrapper function that will accomplish the same. Because of PHP's easy type-casting this can be pretty open-ended:
function array_value ($array, $key) {
return $array[$key];
}
If you just want to return the first item in the array, use the current() function.
return current($foo->getBarArray());
http://php.net/manual/en/function.current.php
Actually, I've written a library which allows such behavior:
http://code.google.com/p/php-preparser/
Works with everything: functions, methods. Caches, so being as fast as PHP itself :)
You can't chain expressions like that in PHP, so you'll have to save the result of array_test() in a variable.
Try this:
function array_test() {
return array(0, 1, 2);
}
$array = array_test();
echo $array[0];
This is too far-fetched, but if you really NEED it to be in one line:
return index0( $foo->getBarArray() );
/* ... */
function index0( $some_array )
{
return $some_array[0];
}
You could, of course, return an object instead of an array and access it this way:
echo "This should be 2: " . test()->b ."\n";
But I didn't find a possibility to do this with an array :(
my usual workaround is to have a generic function like this
function e($a, $key, $def = null) { return isset($a[$key]) ? $a[$key] : $def; }
and then
echo e(someFunc(), 'key');
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.
function test() {
return array(1, 2);
}
list($a, $b) = test();
echo "This should be 2: $b\n";
function test2() {
return new ArrayObject(array('a' => 1, 'b' => 2), ArrayObject::ARRAY_AS_PROPS);
}
$tmp2 = test2();
echo "This should be 2: $tmp2->b\n";
function test3() {
return (object) array('a' => 1, 'b' => 2);
}
$tmp3 = test3();
echo "This should be 2: $tmp3->b\n";
Extremely ghetto, but, it can be done using only PHP. This utilizes a lambda function (which were introduced in PHP 5.3). See and be amazed (and, ahem, terrified):
function foo() {
return array(
'bar' => 'baz',
'foo' => 'bar',
}
// prints 'baz'
echo call_user_func_array(function($a,$k) {
return $a[$k];
}, array(foo(),'bar'));
The lengths we have to go through to do something so beautiful in most other languages.
For the record, I do something similar to what Nolte does. Sorry if I made anyone's eyes bleed.
After further research I believe the answer is no, a temporary variable like that is indeed the canonical way to deal with an array returned from a function.
Looks like this will change starting in PHP 5.4.
Also, this answer was originally for this version of the question:
How to avoid temporary variables in PHP when using an array returned from a function
Previously in PHP 5.3 you had to do this:
function returnArray() {
return array(1, 2, 3);
}
$tmp = returnArray();
$ssecondElement = $tmp[1];
Result: 2
As of PHP 5.4 it is possible to dereference an array as follows:
function returnArray() {
return array(1, 2, 3);
}
$secondElement = returnArray()[1];
Result: 2
As of PHP 5.5:
You can even get clever:
echo [1, 2, 3][1];
Result: 2
You can also do the same with strings. It's called string dereferencing:
echo 'PHP'[1];
Result: H
If it is just aesthetic, then the Object notation will work if you return an object. As far as memory management goes, no temporary copy if made, only a change in reference.
Short Answer:
Yes. It is possible to operate on the return value of a function in PHP, so long as the function result and your particular version of PHP support it.
Referencing example2:
// can php say "homer"?
// print zoobar()->fname; // homer <-- yup
Cases:
The function result is an array and your PHP version is recent enough
The function result is an object and the object member you want is reachable
There are three ways to do the same thing:
As Chacha102 says, use a function to return the index value:
function get($from, $id){
return $from[$id];
}
Then, you can use:
get($foo->getBarArray(),0);
to obtain the first element and so on.
A lazy way using current and array_slice:
$first = current(array_slice($foo->getBarArray(),0,1));
$second = current(array_slice($foo->getBarArray(),1,1));
Using the same function to return both, the array and the value:
class FooClass {
function getBarArray($id = NULL) {
$array = array();
// Do something to get $array contents
if(is_null($id))
return $array;
else
return $array[$id];
}
}
Then you can obtain the entire array and a single array item.
$array = $foo->getBarArray();
or
$first_item = $foo->getBarArray(0);
Does this work?
return ($foo->getBarArray())[0];
Otherwise, can you post the getBarArray() function? I don't see why that wouldn't work from what you posted so far.
You could use references:
$ref =& myFunc();
echo $ref['foo'];
That way, you're not really creating a duplicate of the returned array.