1

Seems strange I can't find an answer to this, but here goes:

This:

foreach ($stuffs as $stuffRow) {
    foreach ($stuffRow as $stuff) {
        if($stuff=== null){
            unset($stuff);
        }
    }
}

is not working.

I know I shouldn't say "isn't working", but that's all I've got. The if condition works; I've tested it. However, when I apply unset, the key=>value is still there.

Note: PHP 5.3

Many thanks in advance!

1 Answers1

1

While this might work (i never do it this way and not tested it):

foreach ($stuffs as &$stuffRow) {
    foreach ($stuffRow as &$stuff) {
        if($stuff=== null){
            unset($stuff);
        }
    }
}

If i remember correctly, passing by reference isn't a good idea in foreachs (but can't remember why, might have been in the php doc somewhere, maybe someone can clarify in the comments, but i think it's because foreach works on a copy of the array and passing a reference passes the reference to the copy, not the original, though that is just an educated guess). Instead, try this.

foreach ($stuffs as $key1=>$stuffRow) {
    foreach ($stuffRow as $key2=>$stuff) {
        if($stuff=== null){
            unset($stuffs[$key1][key2]);
        }
    }
}

The reason your code didn't work by the way is because foreach loops iterate over a COPY of your array.

HenchHacker
  • 1,616
  • 1
  • 10
  • 16
  • Thank-you! &s don't do it for me. PHP 5.3? Second one works like a beaut! –  Nov 18 '12 at 02:45
  • 2
    'As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);. And as of PHP 5.4.0, call-time pass-by-reference was removed, so using it will raise a fatal error.' -- from the [docs](http://php.net/manual/en/language.references.pass.php) – Mike Nov 18 '12 at 02:48
  • I thought i remembered seeing something like that from the docs ;) – HenchHacker Nov 18 '12 at 02:50