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:13

actually, there is an elegant solution:) The following will assign the 3rd element of the array returned by myfunc to $myvar:

$myvar = array_shift(array_splice(myfunc(),2));
查看更多
忆尘夕之涩
3楼-- · 2019-01-01 16:14
function doSomething()
{
    return $somearray;
}

echo doSomething()->get(1)->getOtherPropertyIfThisIsAnObject();
查看更多
时光乱了年华
4楼-- · 2019-01-01 16:15

This might not be directly related.. But I came to this post finding solution to this specific problem.

I got a result from a function in the following form.

Array
(
    [School] => Array
            (
                [parent_id] => 9ce8e78a-f4cc-ff64-8de0-4d9c1819a56a
            )
)

what i wanted was the parent_id value "9ce8e78a-f4cc-ff64-8de0-4d9c1819a56a". I used the function like this and got it.

array_pop( array_pop( the_function_which_returned_the_above_array() ) )

So, It was done in one line :) Hope It would be helpful to somebody.

查看更多
无与为乐者.
5楼-- · 2019-01-01 16:16

Or something like this, if you need the array value in a variable

$variable = array('a','b','c');
$variable = $variable[$key];
查看更多
栀子花@的思念
6楼-- · 2019-01-01 16:19

The technical answer is that the Grammar of the PHP language only allows subscript notation on the end of variable expressions and not expressions in general, which is how it works in most other languages. I've always viewed it as a deficiency in the language, because it is possible to have a grammar that resolves subscripts against any expression unambiguously. It could be the case, however, that they're using an inflexible parser generator or they simply don't want to break some sort of backwards compatibility.

Here are a couple more examples of invalid subscripts on valid expressions:

$x = array(1,2,3);
print ($x)[1]; //illegal, on a parenthetical expression, not a variable exp.

function ret($foo) { return $foo; }
echo ret($x)[1]; // illegal, on a call expression, not a variable exp.
查看更多
大哥的爱人
7楼-- · 2019-01-01 16:20

This is called array dereferencing. It has been added in php 5.4. http://www.php.net/releases/NEWS_5_4_0_alpha1.txt

update[2012-11-25]: as of PHP 5.5, dereferencing has been added to contants/strings as well as arrays

查看更多
登录 后发表回答