Thanks for the responses guys!
@martinbean I know there would be many ways to do this, an array_map would probably be a better solution, it was just an example to show the issue :) The point that I'm trying to make is that variable scoping is an issue that will always exist in PHP and I'm trying to find the best way to pick it up! I'm not new to programming but I'm relatively new to PHP. I've always used strict typed and compiled languages so I wouldn't run into these issues before.
@kfirba Your response is really interesting! I come from a C++ background where there was never a move away from conditionals, but I think this is a really cool approach. One of the things I like to do is always return from functions right at the start if the data isn't valid. What you're saying is that I shouldn't stop there, I should avoid else conditionals at all cost. Is this a documented programming paradigm that I could read about? Is it mainly a PHP thing or is it encouraged in all languages?
I suppose, in my case, I could do (again, I'm adding extra steps just to ensure that everyone is on the same page, I wouldn't create $id in this case):
$ids = [];
foreach ($details as $detail) {
if (is_array($detail)) {
$id = $detail['id'];
$ids[] = $id;
continue;
}
$id = $detail;
$ids[] = $id;
}
Not bad, but often I wonder about readability in this case. We're getting rid of the else statement, but using continue can often leave a bit more uncertainty on what the code below it should be doing. I've often found it easier to say: "If this is true then it does this, otherwise it does this."
Most of the time when there is a continue, I'd explain it as, "at this point we know that it couldn't have been true in the if statement because we wouldn't be able to reach this point if it was." That all sounds great, but from my experience, I've found that a lot of people struggle to comprehend why we know with absolute certainty the first if statement wasn't true compared to when you use an if else.
So that's why this methodology you've described intrigues me, it makes a lot of case for avoiding bugs and problems but don't you think it could have an adverse effect on readability?