0

Say I have a function/method that returns an array, let's call it ArrayReturner(). But I only want the first element, [0]. Right now I'm doing something like...

$arrayReturned = ArrayReturner();
$varIWant = $arrayReturned[0];

Is there a way to do that in one line without the need for the temporary $arrayReturned array?

Dan Goodspeed
  • 3,484
  • 4
  • 26
  • 35

2 Answers2

2

Try:

$arrayReturned = reset(ArrayReturner());
Jeroen
  • 982
  • 1
  • 6
  • 14
  • 1
    Hmm, that didn't work. I code in strict and it gave the error "Strict Standards: Only variables should be passed by reference", and the value assigned to $varIWant is something else... I'm not even sure where the number came from, but it's not the correct value. – Dan Goodspeed Oct 22 '13 at 00:57
  • @DanGoodspeed you can wrap the array in parentheses: `$arrayReturned = reset((ArrayReturner()));` This way it won't be passing a function by reference, just the value. This will conform to strict standards. – hcoat Oct 22 '13 at 01:26
2

Depends on PHP's version you use.

If you're using PHP < 5.4, then you cannot get that, like ArrayReturner()[0]. That's only possible in PHP >= 5.4.

If you want your code to be portable, that would work with old and new versions, then you'd better stick with that code:

$arrayReturned = ArrayReturner();
$varIWant = $arrayReturned[0];
Yang
  • 8,580
  • 8
  • 33
  • 58
  • Damn, I'm still running 5.3.27. I'm not worried about portableness. It's not worth upgrading just for this little feature, but I guess it's good to know. – Dan Goodspeed Oct 22 '13 at 01:00