PHP: Access Array Value on the Fly

2019-01-01 15:53发布

In php, I often need to map a variable using an array ... but I can not seem to be able to do this in a one liner. c.f. example:

// the following results in an error:
echo array('a','b','c')[$key];

// this works, using an unnecessary variable:
$variable = array('a','b','c');
echo $variable[$key];

This is a minor problem, but it keeps bugging every once in a while ... I don't like the fact, that I use a variable for nothing ;)

9条回答
流年柔荑漫光年
2楼-- · 2019-01-01 16:20

There are several oneliners you could come up with, using php array_* functions. But I assure you that doing so it is total redundant comparing what you want to achieve.

Example you can use something like following, but it is not an elegant solution and I'm not sure about the performance of this;

   array_pop ( array_filter( array_returning_func(), function($key){    return $key=="array_index_you_want"? TRUE:FALSE;    },ARRAY_FILTER_USE_KEY ) );

if you are using a php framework and you are stuck with an older version of php, most frameworks has helping libraries.

example: Codeigniter array helpers

查看更多
皆成旧梦
3楼-- · 2019-01-01 16:23

though the fact that dereferencing has been added in PHP >=5.4 you could have done it in one line using ternary operator:

echo $var=($var=array(0,1,2,3))?$var[3]:false;

this way you don't keep the array only the variable. and you don't need extra functions to do it...If this line is used in a function it will automatically be destroyed at the end but you can also destroyed it yourself as said with unset later in the code if it is not used in a function.

查看更多
路过你的时光
4楼-- · 2019-01-01 16:24

I wouldn't bother about that extra variable, really. If you want, though, you could also remove it from memory after you've used it:

$variable = array('a','b','c');
echo $variable[$key];
unset($variable);

Or, you could write a small function:

function indexonce(&$ar, $index) {
  return $ar[$index];
}

and call this with:

$something = indexonce(array('a', 'b', 'c'), 2);

The array should be destroyed automatically now.

查看更多
登录 后发表回答