Alex
Alex

Reputation: 44295

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]

Upvotes: 1

Views: 2228

Answers (4)

hakre
hakre

Reputation: 197624

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.

Upvotes: 0

searlea
searlea

Reputation: 8378

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.

Upvotes: -1

Baba
Baba

Reputation: 95101

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];

Upvotes: 6

nvanesch
nvanesch

Reputation: 2600

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

Upvotes: 1

Related Questions