What is the most elegant way to "foreach x except y" in PHP?
I want to do something like this:
foreach ($array as $key=>$value except when $key="id") { // whatever } ... without having to put an "if" clause inside the loop body. It is not guaranteed that the "id" will be the first or last element in the array, and I really do not want to cancel or cut the array, because it will be expensive, ugly and will not support the original data. I should also definitely use both the key and the value inside the loop.
Any ideas?
I don't think the if clause is such a problem:
foreach ($array as $key => $value) { if ($key == 'ignore_me') continue; if ($key == 'ignore_me_2') continue; If you want a fancy solution, you can use array_diff_key :
$loop_array = array_diff_key($actual_array, array('ignore_me' => NULL, 'ignore_me_2' => NULL)); foreach ($loop_array as $key => $value) { #... Go with the if clause inside the loop. This is not unusual, it is easiest to read and understand, and it is most effective.
If you have many pass keys, you can build a second hash for verification (in if-clause):
foreach ($array as $key => $value) { if (array_key_exists($key,$skip_keys)) continue; ... } I think that you will always use the IF clause in the inner loop. Of all the parameters that you have already given, this is the only thing I would use for speed and memory consumption
AFAIK you cannot do this without an if in a loop.
As with the keyword, this is "for everyone" and not "for most."
EDIT: for example, soulmerge says you can do this with array_diff_key() , but if you just miss one key, it is more verbose and less than just putting if in a loop.
Another way to compact an if :
// ignore 1,5,8,9 foreach($arr as $key){ if(in_array($key, array(1,5,8,9)) continue; ... }