PHP的foreach仅返回键 [英] PHP foreach that returns keys only

查看:163
本文介绍了PHP的foreach仅返回键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

理论问题,也许没有任何意义,但仍然,也许是一个聪明的回答。

Theoretical question that perhaps does not make any sense but still, maybe there is a clever answer.

我想通过数组进行迭代,并获得其钥匙和东西他们。我做什么一个简单的例子:

I want to iterate through array and get its keys and to something with them. A quick example of what I do:

foreach($array as $key => $value) {
    $other_array[$key] = 'something';
}

现在, PHP混乱探测器尖叫了 $值在此范围内使用。所以我在想,也许这是不是我的阵列访问的最佳途径。

Now, PHP Mess Detector screams that $value is unused in this scope. Therefore I was thinking that perhaps this is not the best way to access keys of my array.

任何想法如何做到这一点,避免不必要的取出我的阵列?是否有任何显著的性能影响......或许我只是被偏执并应随身携带,不浪费任何人的时间愚蠢的问题。)

Any idea how to do it without unnecessarily taking out values out of my array? Does it have any significant performance impact ... or perhaps I am just being paranoid and should carry on without wasting anyone's time with stupid questions :).

推荐答案

您可以做这样的事情。

foreach(array_keys($array) as $key) {
 // do your stuff
}

这将使的的foreach 的迭代由来自阵列,而不是实际的数组中的键的数组。请注意,这可能不是从性能的角度来看,虽然好

That would make the foreach iterate over an array consisting of the keys from your array instead of the actual array. Note that it's probably not better from a performance standpoint though.

这篇关于PHP的foreach仅返回键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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