I recently asked an Application Architect at work to review a php
script I had written to automate some tasks I do weekly in our Help Desk department.
In his review he stated
## Loops
Your loops are good, you didn't do anything bad like calling functions in the condition
for ($i=0; $i < count($array); $i++); is BAD
Honestly, I've never been tempted to do that in my code before but it made me wonder why it would be bad.
I assume it's because, the result of a function might be any value at all and it seems like a perfect way to create an infinite loop and just in general cause unexpected behaviour.
I tried googling but couldn't find any relevant results so I ask:
Why is it bad to call a function in the condition of a for loop?
Note the count($array)
in the comment itself is, to me, a gimme. Of course, you'd want to just cache that. More specifically, I mean in the context of using other more complex functions.
For those that will surely wonder "Why not just ask the guy who wrote it", he's super busy and already took the time to help me, I don't want to push that too far with "Now, can you please explain all of your comments to me?"
"function" as a keyword is only used for defining functions, and cannot be used inside a loop (or inside an "if" or "switch" or other control statement.) The only kinds of functions that can be defined within loops are anonymous functions.
You should not define a function inside a loop because you'll encounter errors unless you add a check before the function declaration to see if the function already exists. if (menuSelect == 2); --> ; is not required in your case.
A function is just a set of instructions, so you could, theoretically, take any function's instructions and put them directly inside the loop, and you have essentially the same thing.
Just as a loop is an embodiment of a piece of code we wish to have repeated, a function is an embodiment of a piece of code that we can run anytime just by calling it into action. A given loop construct, for instance could only be run once in its present location in the source code.
for ($i=0; $i < count($array); $i++); //is not efficient
Yes, this is not efficient to use because in every iteration function being called which is not good. You need to execute this function one time.
$count = count($array);
for ($i= 0; $i < $count; $i++); //is much efficient
Because in this code count
function will execute one time. In your previous code count
function execute multiple times.
There are a couple of reasons I can think of:
count()
example)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With