开发者

How do i get a certain key of an array returned by a function? [duplicate]

开发者 https://www.devze.com 2023-02-17 09:08 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: PHP syntax for dereferencing function result
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

PHP syntax for dereferencing function result

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

echo returnArray()[0];

How do i do that with开发者_运维技巧out assigning the whole array to a variable?


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


This is proposed, but not available yet.

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

We'll see


Without testing for any errors

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

echo returnArray(0);


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

ps: it is a sample of "godlike" function. Function should not return more, than you need.

0

精彩评论

暂无评论...
验证码 换一张
取 消