Jump to content

Accessing element of array returned from function


DataRater

Recommended Posts

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

 

 

 

Link to comment
Share on other sites

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?

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.