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?