問題描述
可能沒有任何意義但仍然可能有一個(gè)聰明的答案的理論問題.
Theoretical question that perhaps does not make any sense but still, maybe there is a clever answer.
我想遍歷數(shù)組并獲取它的鍵和帶有它們的東西.我所做的一個(gè)簡(jiǎn)單的例子:
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';
}
現(xiàn)在,PHP Mess Detector
尖叫著 $value
在此范圍內(nèi)未使用.因此,我在想,這可能不是訪問我的 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
的情況下做到這一點(diǎn)嗎?它是否有任何顯著的性能影響......或者我可能只是偏執(zhí),應(yīng)該繼續(xù)而不用浪費(fèi)任何人的時(shí)間來(lái)回答愚蠢的問題:)
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 迭代由數(shù)組中的鍵而不是實(shí)際數(shù)組組成的數(shù)組.請(qǐng)注意,從性能的角度來(lái)看,它可能不會(huì)更好.
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.
這篇關(guān)于PHP foreach 只返回鍵的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!