Access an Array Returned by a Function
Solution 1
PHP 5.4 added array Dereferencing, here's the example from PHP's Array documentation:
Example #7 Array dereferencing
function getArray() {
return array(1, 2, 3);
}
// on PHP 5.4
$secondElement = getArray()[1];
// previously
$tmp = getArray();
$secondElement = $tmp[1];
Solution 2
with arrays the answer is no, but you can use objects:
function getData($id) {
// mysql query
return mysql_fetch_object($result);
}
echo getData($id)->name;
Solution 3
Not really. You could define a function to do it, though:
function array_value($array, $key) {
return $array[$key];
}
// and then
echo array_value(getData($id), 'name');
The only other way, which probably won't help you much in this case, is to use list()
which will get you the first n
items in the returned array. You have to know the order of the items in the list beforehand, though:
function test() {
return array(1, 2, 3, 4);
}
list($one, $two, $three) = test();
// now $one is 1, $two is 2, $three is 3
Solution 4
I have asked a similar question some time ago.
The short answer is no, you can not. Yet, if you just need the first value in the array, you can use reset():
function getArray()
{
array('la', 'li', 'lu');
}
echo reset(getArray()); // echos "la"
Related videos on Youtube
Jordan Satok
Updated on April 16, 2022Comments
-
Jordan Satok about 2 years
Is there anyway to directly access the data returned in an array without a temporary variable?
Currently, my code is as follows:
function getData($id) { // mysql query return mysql_fetch_array($result); } $data = getData($id); echo $data['name'];
Is there a direct way to get the returned data without the temporary variable?