Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 550
Jordan Satok Avatar asked Nov 02 '09 23:11

Jordan Satok


People also ask

How do I find a repeated array?

Duplicate elements can be found using two loops. The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element. The inner loop will be used to compare the selected element with the rest of the elements of the array.

How do you return an array without duplicates?

Use the filter() method: The filter() method creates a new array of elements that pass the condition we provide. It will include only those elements for which true is returned. We can remove duplicate values from the array by simply adjusting our condition.

Does array accept duplicate values?

The standard way to find duplicate elements from an array is by using the HashSet data structure. If you remember, Set abstract data type doesn't allow duplicates. You can take advantage of this property to filter duplicate elements.

Which function is used to remove duplicate values from an array?

The array_unique() function removes duplicate values from an array.


3 Answers

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];
like image 126
joemaller Avatar answered Oct 29 '22 11:10

joemaller


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;
like image 4
user187291 Avatar answered Oct 29 '22 13:10

user187291


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
like image 3
Paige Ruten Avatar answered Oct 29 '22 12:10

Paige Ruten