問題描述
可能沒有任何意義但仍然可能有一個聰明的答案的理論問題.
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
在此范圍內未使用.因此,我在想,這可能不是訪問我的 array
的 keys
的最佳方式.
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 只返回鍵的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!