简体   繁体   中英

Is it possible to inline access a PHP array?

In PHP I have the following construct

$a = array(-1 => '-', 0 => '?', 1 => '+')[1];

which gives a syntax error. Is it still possible to do such things in one convenient line avoiding multiple if/else clases or switch/select statements? I was thinking at python where this work fine:

a = {-1:'-', 0:'?', 1:'+'}[1]

It works in PHP but only 5.5.0alpha1 - 5.5.0beta2 you should use variables for now until a stable version is released.

$array =  array(-1 => '-', 0 => '?', 1 => '+');
print $array[1];

Another Intresting thing is that PHP Support Function Array Dereferencing in PHP 5.4 which means just wrapping your array in a function would make it work

function __($_) {
    return $_;
}

print __(array(-1 => '-', 0 => '?', 1 => '+'))[1];

You could create a helper function so you can do it in one line.

function array_get($array, $key)
{
    return $array[$key]
}

print array_get(array(-1 => '-', 0 => '?', 1 => '+'), 1);

The one-line way is:

$a = array_pop(array_slice(array(-1 => '-', 0 => '?', 1 => '+'), 1, 1));

Or in the general case:

$x = array_pop(array_slice(foo(), $offset, 1));

Which is of course horrible.

Regardless which PHP version, if you're after that, you should have something in your function set:

function deref($subject) {
    return $subject;
}

function deref_array($array, $key) {
    return $array[$key];
}

This pair of very rudimentary functions allows you to tell the PHP parser most often what you need and mean:

$a = deref_array(array(-1 => '-', 0 => '?', 1 => '+'), 1);

In your concrete case you only need the second function, but the first one often is useful, too.

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