PHP – Best Practices for Return Values

PHPweb-development

For PHP, best practices, I have read somewhere that if you assign your data to a variable it takes almost no memory or resource.

So let's say I have this function that return a count.

public function returnCount($array){
    return count($array);
}

or if this is better?

public function returnCount($array){
    $count = count($array);
    return $count;
}

Best Answer

This is not a php-only issue, therefore there might be potential duplicate questions. Generally

The first approach (return count(...)) is faster to read and in some cases will produce faster code, because of the time consumed to instantiate the variable $count.

The second approach is kind of easier to debug and maintain. Each operations takes place in a distinct line, which is easier to isolate hence debug, since some IDEs can place a debug breakpoint to the exact line. It is also easier to maintain/extend in case you want for example to log the result or do another operation with this.

I do not believe there is a "better" way, or that it matters so much for a one/two liner. I would use the first one and then refactor it in case it had to be extended.

What many people would agree upon is that something like:

log("$array"); return count($array) * 4 - ($array4==null)?(count($array2)^94):int_val($xyz);

should better be broken into different lines.

Related Topic