DataRater Posted March 12, 2010 Share Posted March 12, 2010 PHP 5 I want to simply access an element of array returned from a function. Assume I've got a function Function ReturnArray(){ $Array = array( 'A' => 'Fred', 'B' => 'George' ); return($Array); } I would like to access it like this $Var = ReturnArray()['A']; But it doesn't work. Any ideas? Stephen Quote Link to comment https://forums.phpfreaks.com/topic/195006-accessing-element-of-array-returned-from-function/ Share on other sites More sharing options...
GingerRobot Posted March 12, 2010 Share Posted March 12, 2010 AFAIK, there's no way to do that...just assign the returned value to a variable and then read the index. It would be a bit of a strange thing to do anyhow; if you want to read both indexes then you'd have to do the computation twice...and if you don't want to read both values, why return them? Edit: Forgot about list(). You could do this: list(,$var) = ReturnArray(); My point still stands though -- why repeat the function call? Quote Link to comment https://forums.phpfreaks.com/topic/195006-accessing-element-of-array-returned-from-function/#findComment-1025178 Share on other sites More sharing options...
salathe Posted March 12, 2010 Share Posted March 12, 2010 Function array dereferencing (which is what you're trying to do) is not available in PHP. You'll need to use more normal methods of getting the value that you want, like: $arr = ReturnArray(); $var = $arr['A']; P.S. list won't work because of the string indexes. Quote Link to comment https://forums.phpfreaks.com/topic/195006-accessing-element-of-array-returned-from-function/#findComment-1025180 Share on other sites More sharing options...
DataRater Posted March 12, 2010 Author Share Posted March 12, 2010 The functions returns an array of values and I only ever want one of them. So I have one function instead of many. Quote Link to comment https://forums.phpfreaks.com/topic/195006-accessing-element-of-array-returned-from-function/#findComment-1025182 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.