Page 1 of 1

Using [] in function call

Posted: Tue Jan 08, 2008 6:14 pm
by mrl72
Hi - I'm beginning learning PHP so apolgoize if this is a really dumb question. I am looking at some code and see a line as follows:

$var = myfunction($var1, $var2, $var3)[1];

I don't understand what the [1] at the end of the line is for? Also, this is throwing a parse error unexpected '['.

Any help appreciated.

Thanks.

Re: Using [] in function call

Posted: Tue Jan 08, 2008 6:35 pm
by superdezign
mrl72 wrote:$var = myfunction($var1, $var2, $var3)[1];
Whoever wrote it was trying to access an array element from an array returned from the function. The problem is that you can't do that in PHP, not with that syntax. You can do it in JavaScript, though.

If you want to get a portion of the array, you could save the array into a variable and then extract what you want, or use the list() construct.

Posted: Tue Jan 08, 2008 6:53 pm
by mrl72
Ah yes I see. I looked in the function and I can see it returning an array.

return array( $var1, $var2, $var3) etc.

So I could use:

$var = myfunction($var1, $var2, $var3);

$var0 = $var[0];
$var1 = $var[1];
$var2 = $var[3];

Something like that?

Posted: Tue Jan 08, 2008 6:57 pm
by superdezign
Mmhmm.

Posted: Tue Jan 08, 2008 7:31 pm
by mrl72
feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


eh.. just taking this one step further. What if the function is returning an array of arrays? Would I be able to access them in the same way?

Code: Select all

function myfunction()
{

$var1=array("apple","banana");
$var2=array("pear","grapefruit");

return array( $var1, $var2);

}

$var=myfunction();

$arr1=$var[0];
$arr2=$var[1];

$apple=$arr1[0];
$banana=$arr1[1];
etc. ?


feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Tue Jan 08, 2008 8:27 pm
by Ambush Commander
Yes. You can also chain them together, like $apple = $var[0][0]. Arrays can also be nested, so a more compact way of doing myfunction is:

Code: Select all

function myfunction()
{
return array( array("apple","banana"), array("pear","grapefruit"));
}
although not necessarily more readable.

See also list()