简体   繁体   中英

How do I get the value in a single element array in one line without strict warnings in PHP 5.3

Given a function which returns an array;

function return_me_an_array() {
  return array('my_value');
}

How can I call it and get a single value (whether, first, last or only) from the array in an elegant fashion (yes I know this is PHP!)

If I do this

$var = reset(return_me_an_array());

I get the following PHP strict error:

Strict warning: Only variables should be passed by reference

Likewise each of these give the same warning.

$var = array_shift(return_me_an_array());
$var = array_pop(return_me_an_array());

I know I can do this:

$temp = return_me_an_array();
$var = $reset($temp);

But having to do it over two statements is pretty horrible.

Is there a good way to do this?

On the face of it this is similar to How to return an array and get the first element of it in one line in PHP? but the accepted answer uses reset - so I think this is different; I'm either looking for a solution that doesn't give strict warnings, or to be told what I want is impossible.

I'm also aware the PHP 5.4 has introduced array dereferencing (eg return_me_an_array()[0] ) but alas I am currently using 5.3.

Edit after being closed : How is this too localized? This is a general question about how to write elegant PHP. Or is it the case that so few people care about elegant PHP it is "an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet"?

Use this:

$var = current(return_me_an_array());

Demo: http://3v4l.org/Ruj5e

Manual: http://php.net/manual/en/function.current.php

Define your own array methods for that purpose:

function my_reset($array)
{
    return reset($array);
}

echo my_reset(return_me_an_array());

UPD:

There is even more elegant way, check Returning References manual

Use this:

$var = array_shift($var = return_me_an_array());

Link to codepad

Ok can't he just supress the error? Or is that not elegant enough?

$var = @reset(return_me_an_array());

Or like shared at https://stackoverflow.com/a/6726277/881551

$var = reset( ( return_me_an_array() ) );

Both tested and work fine for the purpose of circumventing the strict notice which is what is essentially being asked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM