How to get a specific key of an array returned by a function?

Possible duplicate:
PHP syntax for dereference function result

function returnArray(){
  $array = array(
     0 => "kittens",
     1 => "puppies"
  );
  return $array;    
}

echo returnArray()[0];

How can I do this without assigning an entire array to a variable?

+3
source share
4 answers

Why don't you pass a parameter in your function?

function returnArray($key=null){
  $array = array(
     0 => "kittens",
     1 => "puppies"
  );
  return is_null($key) ? $array : $array[$key];    
}

echo returnArray(0); // only 0 key
echo returnArray(); // all the array
+9
source

This is proposed, but not yet available.

http://wiki.php.net/rfc/functionarraydereferencing

We'll see

+3
source

No error testing

function returnArray($i){
  static $array = array(
             0 => "kittens",
             1 => "puppies"
         );
  return $array[$i];    
}

echo returnArray(0);
+3
source

There is no way to do this without any temporary variable.

ps: this is an example of a "god-like" function. The function should not return more than you need.

+1
source

All Articles