Today while working on text analysing tool for blogs, I found PHP behavior very strange for me and just couldn't wrap my head around it. While normalizing text, I was trying to remove words below minimum length, so I wrote this in my normalization method:
if ($this->minimumLength > 1) {
foreach ($string as &$word)
{
if (strlen($word) < $this->minimumLength) {
unset($word);
}
}
}
Strangely, this would leave some words below allowed length in my array. After searching my whole class for mistakes, I gave a shot at this:
if ($this->minimumLength > 1) {
foreach ($string as $key => $word)
{
if (strlen($word) < $this->minimumLength) {
unset($string[$key]);
}
}
}
And voila! This worked perfectly. Now, why would this happen ? I checked out PHP Documentation and it states:
If a variable that is PASSED BY REFERENCE is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.
Does foreach
act here as a calling environment
because it has it's own scope?