1

I feel stupid for asking this cause it seems so basic but it's really bugging me.

I have a method that returns an array with a single element. I just want it to return the element not wrapped in an array. I tried this.

return $f->getValue()[0];

and it gives an error but if I save it to a variable, it works fine.

$v = $f->getValue();
return $v[0];

I can't figure it out....

Saad Farooq
  • 13,172
  • 10
  • 68
  • 94

5 Answers5

4

It's available only since PHP 5.4: http://codepad.viper-7.com/VHOW0o

meze
  • 14,975
  • 4
  • 47
  • 52
4

What you are trying to do, is called array dereferencing, and is only possible in PHP as of version 5.4 (if you scroll up a few lines in the documentation article I linked to, you'll see it mentioned).

Decent Dabbler
  • 22,532
  • 8
  • 74
  • 106
2

Use reset().

<?php return reset( $f->getValue() ); ?>

Edit: reset() is probably superior to current() as it also makes sure that the internal pointer is reset, despite it not making much difference if the array only contains one element.

kjetilh
  • 4,821
  • 2
  • 18
  • 24
1

As far as I know since you are returning an array you only can get an array. You can instead save the array to a variable in the class (accessible by $f->myArray) and then return just the string portion. Or the other option is to do what your second example is and return the array and retrieve the string from it.

Sam
  • 20,096
  • 2
  • 45
  • 71
0

have you tried this

         <?php
           return array_shift(array_values($array));
         ?>

Get the first element of an array

Community
  • 1
  • 1
srs
  • 68
  • 1
  • 1
  • 9