I've been experiencing this weird behavior on a simple PHP snippet. I have a foreach
loop that needs to iterate through multiple users and increment a variable for each user unless the user's id is a member of a given array.
Right now, the foreach is looping through users with IDs 1 through 1000 and it works OK except for user ID 74, which should be skipped but is not. Users with ID 75-81 are skipped correctly
The code:
$exceptions = array(74,75,76,77,78,79,80,81);
foreach ($users as $u)
{
if (array_search($u->id, $exceptions) == false)
{
// not found on the array, so no skipping
$i++;
}
}
The above is an over-simplification of the code, but it helps reproduce the issue. The array is formed dynamically from a separate database query and is well formed. When doing a print_r
for the array is comes out as expected:
Array
(
[0] => 74
[1] => 75
[2] => 76
[3] => 77
[4] => 78
[5] => 79
[6] => 80
[7] => 81
)
The issue is that no errors are thrown, the loop iterates through the 1000 users correctly but only excludes users 75 to 81. I noticed that only the first array element gets "ignored" so I worked around this by defining a non-existing user ID (0) as the first array element, which helped. But since it's an ugly solution I've been trying to figure this out all afternoon. As you may note above, I'm not using strict comparisons so that shouldn't be the issue.
During debugging, I changed the code to write some logs. every time a user ID was being checked and wasn't present in the $exclusions
array, a log entry would be added. Unsurprisingly, "74 was not found in exclusions" was logged.
I did some further tracing only to find out that on the first array element, the IF clause evaluated to false.
At this point this is merely academic curiosity, as the ugly workaround works, but does anybody have a clue why this happens?