开发者

I Don't Understand This Array Syntax

开发者 https://www.devze.com 2023-02-05 14:25 出处:网络
I don\'t understand this array accessing syntax: $target[$segs[count($segs)]] Is it really possible to use variables as multidimensi开发者_运维知识库onal array keys?That might result in an error, i

I don't understand this array accessing syntax:

$target[$segs[count($segs)]]

Is it really possible to use variables as multidimensi开发者_运维知识库onal array keys?


That might result in an error, if $segs is a numerical array with continuous indices only.
Meaning, it would fail for:

array("foo","bar");

but work for

array("foo", 2=>"bar");

Assuming now, that we deal with the first case, then this would work:

$target[$segs[count($segs) - 1]]

First, count($segs) - 1 will be evaluated and return a number. In this case the last index of $segs (provided it is a numerical array).

$segs[count($segs) - 1] will therefore return the last element in $segs. And whatever that value is, will be used as index for $target[...].


To sum up: It is nested array indexing and evaluated inside out.

See it in action.

Whether or not such a method is necessary depends on the problem you are trying to solve. If you don't know where you would use such nested, variable array indexing then you probably don't need it.


That syntax is fine, provided $segs is an array. It's worth noting, though, that if you're using a numerically indexed array for $segs, calling count($segs) is a non-existent key because indexing starts at zero.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号