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.
Using [] in function call
Moderator: General Moderators
- superdezign
- DevNet Master
- Posts: 4135
- Joined: Sat Jan 20, 2007 11:06 pm
Re: Using [] in function call
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.mrl72 wrote:$var = myfunction($var1, $var2, $var3)[1];
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.
feyd | Please use
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]
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];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]- Ambush Commander
- DevNet Master
- Posts: 3698
- Joined: Mon Oct 25, 2004 9:29 pm
- Location: New Jersey, US
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:
although not necessarily more readable.
See also list()
Code: Select all
function myfunction()
{
return array( array("apple","banana"), array("pear","grapefruit"));
}See also list()