OnklMaps OnklMaps - 26 days ago 9
PHP Question

Does asking twice give bad performance?

Example 1:

function getMilk() {
if($condition == true) return "Milk for you, madam";
else return false;
}

if(getMilk()) echo getMilk();


Does the first example make PHP run for milk twice?

Example 2:

echo getMilk(); // don't check for milk first, just get it if they have it


If I was PHP I would rather get the second example. Then I wouldn't have to run to the store checking for milk, then running once more to get it.

Would example 2 be faster/better, or doesn't it matter?

Answer Source

Yes, you are calling the function twice. Avoid doing that (because the function can be expensive to call) by doing one of the following:

$getMilk = getMilk();
if($getMilk) echo $getMilk;

You can reduce this to a one line (but unreadable) format:

if ($getMilk = getMilk()) echo $getMilk;

You can also use an inline if ternary, with a fallthrough:

echo getMilk()?:""; //Will echo the result of getMilk() if there is any or nothing.