E() undefined value - Best practices?

Let’s say I’m using the e() function to echo something if a value is true (or any other optimistic value):

<div <?php e($test, ' class="test"'); ?>></div>

If the variable is not set (maybe not sent to the snippet) it will result in:

Notice: Undefined variable

The nice thing about the e() function is that it’s so short. More code around it would make it a mess quite quickly.

This is a possible workaround that worked but I’m not sure if it’s a good one:

<div <?php e(@$test, ' class="test"'); ?>></div>

Another alternative:

<div <?php e(isset($test) && $test, ' class="test"'); ?>></div>

How would you solve it?

What about using …

!empty($test)

… instead of …

isset($test) && $test

I guess it depends on the content of the variable, but it should do the same with a bit less code?! But I’m not sure if it works, if $test is e.g an empty page collection. Needs to be tested …

1 Like

It should work. According to the docs, empty() is the equivalent of !isset($var) || $var == false (and an empty collection will still return true), not false.

I would in any case avoid using @.

1 Like