February 27, 2012
One line code to get one value from function that returns an array
Question by Salman A
Possible Duplicate:
Parse error on explode('-','foo-bar')[0] (for instance)
In PHP there are functions that return an array, for example:
$a = parse_url("http://stackoverflow.com/q/9461027/87015");
echo $a["host"]; // stackoverflow.com
My question is how to combine the above two statements into a single statement. This (is something that works in JavaScript but) does not work:
echo parse_url("http://stackoverflow.com/q/9461027/87015")["host"];
Answer by Starx
You can do a little trick instead, write a simple function
function readArr($array, $index) {
return $array[$index];
}
Then use it like this
echo readArr(parse_url("http://stackoverflow.com/questions/9458303/how-can-i-change-the-color-white-from-a-uiimage-to-transparent"),"host");