Protecting against 'no code' foreach loops in PHP

Viewed 68

I'm coming to PHP after years of using C# and can't believe I've just spent hours trying to debug this. Basically, no matter how many posts I had in my collection, only the last one in the collection was ever updated.

foreach($posts as $post); {
    $post->name = 'updated';
    $post->save();
}

Of course, the problem was the semi-colon at the end of the foreach, meaning that did nothing, and the block of code I was expecting to run for each item in the array, only ran once after the empty foreach loop had processed. The code didn't fall over as $post has the value of the last item in the collection. I'm used to C# protecting me against this sort of stupidity on my part, as $post would only be in scope for the duration of the foreach loop.

My question is therefore, is there a way to protect against this in PHP, so at the very least the code fails at run time with $post either being null or not defined?

1 Answers

Keeping in mind that the question asks for a protection at runtime, the short answer is no.

According to the PHP documentation there are only 2 types of scopes in PHP: the global scope (so the variable is available everywhere) and a local function scope (the variable is only available inside the function that declares it).

Since your code is valid, you can only get a warning if the $posts array has no elements and, because of that, $post is undefined. That will trigger just a notice:

Notice: Undefined variable: post
Related