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?
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.
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.
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.
The array_unique() function removes duplicate values from an array.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With