Last active
May 15, 2025 10:22
-
-
Save vielhuber/15b8ab1523cde1f4b01a66a31de95181 to your computer and use it in GitHub Desktop.
foreach unset #php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* problem */ | |
$array = ['a' => 1, 'b' => 2, 'c' => 3]; | |
foreach ($array as $array__key => $array__value) { | |
echo 'iterating over '.$array__key."\n"; | |
if ($array__value === 2) { | |
unset($array['c']); | |
} | |
} | |
// iterating over a | |
// iterating over b | |
// iterating over c (❗this is the problem!) | |
print_r($array); // ['a' => 1, 'b' => 2] | |
/* solution */ | |
$array = ['a' => 1, 'b' => 2, 'c' => 3]; | |
foreach ($array as $array__key => $array__value) { | |
if (!array_key_exists($array__key, $array)) { continue; } | |
echo 'iterating over '.$array__key."\n"; | |
if ($array__value === 2) { | |
unset($array['c']); | |
} | |
} | |
// iterating over a | |
// iterating over b | |
print_r($array); // ['a' => 1, 'b' => 2] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment