Is it more efficient to check the empty values ​​in php?


In some cases when an empty value is not an issue, I do not check the variable.

For example:

$fruits = array("apple","banana");
    foreach ($fruits as $a) {
    $res .= ", $a";

echo "This are the fruits you like: ".$res;

Now, if $fruits happens to be empty, this is not an problem, simply the list will be empty (I know this is not very elegant and I could use a conditional statement to change the answer to "You do not like any fruit", but it’s just an example!).

I’m just wondering if in general it is more efficient to check if the array is empty anyway. In short, is this better from a performance point of view or isn’t there any actual difference:

if (!empty($fruits)) foreach()... and so on

Thanks, kind regards

Any performance gains would be negligible. This is called micro-optimization. Focus on writing good code and stop worrying about micro-optimizations.

I'd go for something like this:

if(!empty($fruit) && is_array($fruit)){
    echo "This are the fruits you like: " . implode(", ", $fruit);