Reputation: 13402
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....
Upvotes: 1
Views: 115
Reputation: 4976
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.
Upvotes: 2
Reputation: 68
have you tried this
<?php
return array_shift(array_values($array));
?>
Get the first element of an array
Upvotes: 0
Reputation: 22783
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).
Upvotes: 4
Reputation: 15087
It's available only since PHP 5.4: http://codepad.viper-7.com/VHOW0o
Upvotes: 4
Reputation: 20486
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.
Upvotes: 1