Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using boolean function return or setting the return to a variable?

Tags:

php

I was wondering whether it is more efficient to set a function's return to a variable, since if you were to use it in arguments, wouldn't they have to go through the function again?

For instance:

function check() {
    foreach() {
        // insert long foreach loop here
        return true;
    }
}

if(check() == 1 || check() === true) {
    // had to go through the function twice?
}

$check = check();
if($check == 1 || $check === true) {
    // only has to go through the function once
}

I was wondering whether PHP somehow saved the results from the first run through the function or whether it goes through the function each time (which seems inefficient if the arguments are the same - in this case, none).

If anyone wants to suggest a better title or edit it, go ahead.


1 Answers

It goes through each time. Save it to a variable beforehand, as in your second example.

like image 56
Logan Serman Avatar answered Apr 20 '26 04:04

Logan Serman