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....

5 Answers 5

4

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

Sign up to request clarification or add additional context in comments.

Comments

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).

Comments

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.

1 Comment

It's annoying that this requires a workaround... at least they fixed it in 5.4
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.

2 Comments

I may be wrong though. Why do you want to return an array if you only want the string?
It's a library... they are cases when it returns arrays of strings
0

have you tried this

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

Get the first element of an array

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.