2

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("https://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("https://stackoverflow.com/q/9461027/87015")["host"];

Note: function array dereferencing is available since PHP 5.4; the above code works as-is.

Salman A
  • 262,204
  • 82
  • 430
  • 521

2 Answers2

2

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");
Starx
  • 77,474
  • 47
  • 185
  • 261
1

Honestly, the best way of writing your above code is:

$a = parse_url("http://stackoverflow.com/q/9461027/87015");
echo $a["scheme"];
echo $a["host"];

Isn't that what I originally posted?

Yes. Depending on context you may want a better name than $a (perhaps $url), but that is the best way to write it. Adding a function is not an attractive option because when you revisit your code or when someone reads your code, they have to find the obscure function and figure out why on earth it exists. Leave it in the native language in this case.

Alternate code:

You can, however, combine the echo statements:

$a = parse_url("http://stackoverflow.com/q/9461027/87015");
echo $a['scheme'], $a['host'];
Levi Morrison
  • 19,116
  • 7
  • 65
  • 85
  • I don't think this helps the OP in any way. Its same as he asks. and Alternative is not what he asks for. – Starx Feb 27 '12 at 07:07
  • He provides two lines of code for is 'example' of what he wants. Mine is also two lines. I certainly think it helps to let him know he's trying to do something he shouldn't. – Levi Morrison Feb 27 '12 at 07:11
  • Even if there was a way to do this in PHP, there's also no need to run `parse_url()` on the same string more than once. Even in javascript you'd probably use a variable. The only exception I can imagine is if you're sure you only need it once (to extract only 'host' for instance). – Wesley Murch Feb 27 '12 at 07:26