从函数返回的PHP数组中获取元素 [英] Getting element from PHP array returned by function

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

问题描述

我不确定这是否可行,但是我不知道该怎么办...

I'm not sure if this is possible, but I can't figure out how to do it if it is...

我想从函数返回的数组中获取特定元素,而无需先将其传递到数组中……

I want to get a specific element out of an array that is returned by a function, without first passing it into an array... like this...

$item = getSomeArray()[1];


function getSomeArray(){
     $ret = Array();
     $ret[0] = 0;
     $ret[1] = 100;
     return $ret;
}

正确的语法是什么?

推荐答案

PHP不能做到这一点,这是众所周知的限制.您完全有权利怀疑您在开玩笑吗?".抱歉.

PHP cannot do this yet, it's a well-known limitation. You have every right to be wondering "are you kidding me?". Sorry.

如果您不介意生成 E_STRICT 警告,则可以随时退出带有 reset array_slice 可以安排您想保留的第一个或最后一个,但这可能会使事情走得太远

If you don't mind generating an E_STRICT warning you can always pull out the first and last elements of an array with reset and end respectively -- this means that you can also pull out any element since array_slice can arrange for the one you want to remain first or last, but that's perhaps taking things too far.

但绝望的不是:(目前即将发布)PHP 5.4版本将完全包含此功能(名称为

But despair not: the (at this time upcoming) PHP 5.4 release will include exactly this feature (under the name array dereferencing).

更新:我只是想到了另一种可行的技术.可能有很好的理由,我从未使用过它,也没有看到它使用过,但是从技术上讲,它确实可以胜任.

Update: I just thought of another technique which would work. There's probably good reason that I 've never used this or seen it used, but technically it does the job.

// To pull out Nth item of array:
list($item) = array_slice(getSomeArray(), N - 1, 1);

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

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