从函数返回时,访问数组元素 [英] Accessing an array element when returning from a function

查看:116
本文介绍了从函数返回时,访问数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有的通过谷歌(和我自己的经验)搜索显示,在PHP当它从在同一行的函数调用返回,你不能抢的数组元素。例如,你不能做的:

 呼应的getArray()[0];

不过,我遇到一个整洁的小窍门:

 回声$ [0] {$ {FALSE} =的getArray()!};

它的实际工作。问题是,我不知道的为什么的工作原理。如果有人可以解释,那将是巨大的。

感谢。


解决方案

 回声$ [0] {$ {FALSE} =的getArray()!};

这是它的工作原理,分步实施

  $ {FALSE} =的getArray()

具有空名称的的getArray的结果分配给一个变​​量(''或NULL的工作,而不是假的)

 !$ {FALSE} =的getArray()

否定上述数值,把它布尔值false

  $ {!$ {FALSE} =的getArray()}

在previous(假)的值转换为(空)字符串,并使用此字符串作为变量名。也就是说,这是从步骤1中,等于的getArray的结果的变量。

  $ {!$ {FALSE} =的getArray()} [0];

需要的空的变量指标,并返回数组元素。

同样的想法的更多的变化。

 回声$ {1 | $ {1} =的getArray()} [1];
回声$ [1] {''$ =阵列的getArray()};函数P(安培; $ A,$ B){$ a = $ B;返回'_'; }
回声$ {对($ _,的getArray())} [1];

至于为什么的getArray()[0] 不起作用,这是因为PHP团队不知道如何得到它的工作。

Some searching through Google (and my own experience) shows that in PHP you can't grab an array element when it's been returned from a function call on the same line. For example, you can't do:

echo getArray()[0];

However, I've come across a neat little trick:

echo ${!${false}=getArray()}[0];

It actually works. Problem is, I don't know why it works. If someone could explain, that would be great.

Thanks.

解决方案

echo ${!${false}=getArray()}[0];

This is how it works, step by step

${false}=getArray()

assigns the result of getArray to a variable with an empty name ('' or null would work instead of false)

!${false}=getArray()

negates the above value, turning it to boolean false

 ${!${false}=getArray()}

converts the previous (false) value to an (empty) string and uses this string as a variable name. That is, this is the variable from the step 1, equal to the result of getArray.

${!${false}=getArray()}[0];

takes index of that "empty" variable and returns an array element.

Some more variations of the same idea

echo ${1|${1}=getArray()}[1];
echo ${''.$Array=getArray()}[1];

function p(&$a, $b) { $a = $b; return '_'; }
echo ${p($_, getArray())}[1];

As to why getArray()[0] doesn't work, this is because php team has no clue how to get it to work.

这篇关于从函数返回时,访问数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆