沃梦达 / 编程问答 / php问题 / 正文

PHP foreach 只返回键

PHP foreach that returns keys only(PHP foreach 只返回键)

本文介绍了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 Mess Detector 尖叫着 $value 在此范围内未使用.因此,我在想,这可能不是访问我的 arraykeys 的最佳方式.

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.

知道如何在不不必要地从我的 array 中取出 values 的情况下做到这一点吗?它是否有任何显着的性能影响......或者我可能只是偏执,应该继续而不用浪费任何人的时间来回答愚蠢的问题:)

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 只返回键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:PHP foreach 只返回键

基础教程推荐