Access an Array Returned by a Function [duplicate]
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?
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];
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;
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
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"
Unfortunately, no.
You could do something like this:
function getData($id) {
// mysql query
return mysql_fetch_array($result);
}
foreach(getData("your_input_query") as $key=>$value){
echo $value;
}
And then you could use a switch or if/else statements to only perform other functions on the returned data if they equal a certain value (in this case, if $key == 'name').
In short, it's much easier just to set that temporary variable and access it that way.
I think the verbage is a little wrong for your question, but I think are looking to accomplish something like this:
echo getData($id)->someArrayOffset;
While you can do this with mysql_fetch_object, I'll show you how you can do this using ArrayObject in PHP5, or by returning your own object in PHP 4 so that you can find a usefulness for it outside of function that return objects for you. Here's your same function using ArrayObject in PHP5:
function getData($id) {
// mysql query
return new ArrayObject( mysql_fetch_array($result) );
}
echo getData($id)->name;
精彩评论