Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most elegant way to do "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 body of the loop. It is not guaranteed that "id" will the be the first or last element in the array, and I don't really want to unset or slice the array, because that will be expensive, ugly, and not maintain the original data. I also definitely need to use both key and value inside the loop.

Any ideas?

like image 597
sanbikinoraion Avatar asked Apr 24 '09 09:04

sanbikinoraion


1 Answers

I don't think that 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) {
    #...
like image 64
soulmerge Avatar answered Sep 17 '22 18:09

soulmerge