Reputation: 40
Is a PHP function done on the server side each time I call it? I am asking this because I wan't to know if it affects my performance.
Example:
<?php
function really_long_loop() {
$array = array();
for ($i=1; $i < 1000; $i++) {
array_push($array, $i);
}
return $array;
}
function FirstFunction() {
$get_loop = really_long_loop();
}
function SecondFunction() {
$get_loop = really_long_loop();
}
?>
In this example does it do the long loop twice, or just once?
Upvotes: 1
Views: 57
Reputation: 14992
Now let's run your functions. In this case, you'll be running the loop twice. That's intended, of course.
<?php
FirstFunction();
SecondFunction();
?>
You could apply your function's return to a variable, then the variable would hold the value, and the loop wouldn't be executed again when you call this variable.
If you'll need the same value from the loop in two places in your page, you could do this:
<?php
$loopResult = really_long_loop();
?>
Your $loopResult
variable will hold the value for the rest of the code execution, except inside functions, where you would need to pass this variable as a parameter.
When you call , for example, $foo = $loopResult
, the loop function won't run again.
Upvotes: 2