3

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 without assigning the whole array to a variable?

Community
  • 1
  • 1
barin
  • 4,481
  • 6
  • 28
  • 29

4 Answers4

9

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
guillaumepotier
  • 7,369
  • 8
  • 45
  • 72
3

This is proposed, but not available yet.

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

We'll see

KingCrunch
  • 128,817
  • 21
  • 151
  • 173
3

Without testing for any errors

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

echo returnArray(0);
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
1

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.

zerkms
  • 249,484
  • 69
  • 436
  • 539
  • The return value of the example code is just a list. Whats the issue with that? – KingCrunch Mar 15 '11 at 09:53
  • @KingCrunch: the issue with what? Every function should return exactly the needed amount of data. Not more or less. Thus you never ask about how to dereference just one item of million returned. – zerkms Mar 15 '11 at 09:54
  • Imagine the function is called `getCategories()`. Than a list is already the needed data. Its not reducible without destroying the meaning. – KingCrunch Mar 15 '11 at 09:59
  • 2
    What if you do not control the function? – barin Mar 15 '11 at 09:59
  • @barin: you always can create one more function, that returns only what you need. – zerkms Mar 15 '11 at 10:10
  • @KingCrunch: sure, and that is why if you need just "some_specific_category" then you need to call "GetSomeCategory()" function. – zerkms Mar 15 '11 at 10:10