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

 

 

 

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?

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.