function returned array element in single statement
hi all,
i am wondering if there is any way to access array elements in a single statement, without defining new function or using loop etc...
using arrary syntax: getallheaders()['User-Agent']; or object syntax: getallheaders()->User-Agent; or similar. or even a uilt-in function like get_element_by_key(getallheaders(),'User-Agent');
i've been searching for some time but did not find any.
I'm only aware of object/method chaining along those lines. If you know where in the array an item will be, you could use array_slice() on the returned value, but that sounds prone to bugs if the array structure ever changes for any reason, and thus not worth the tiny bit of typing it might save (if any?).
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
function arr2obj(array $arr) { return (object) $arr; }
echo arr2obj(foo())->bar;
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
Thanx for reply, i know there are some easy ways to do it by defining custom functions or storing it in a variable (i am using it by storing in a variable then access as i did not find more easy way), I hope some other guys too want same ? isnt it ?
Actually, all you have to do, apparently, is upgrade to PHP 5.4.
As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.
Example #7 Array dereferencing
PHP Code:
<?php
function getArray() {
return array(1, 2, 3);
}
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
Bookmarks