Skip to content
Advertisement

PHP if statement: Zero vs ’empty’

I’m creating a WordPress website using the Advanced Custom Fields plugin. I have a set of fields for tennis score results. In the template, I’m showing these fields like this:

<?php if(get_field('my_field')) : ?>
   <?php echo get_field('my_field'); ?>
<?php endif; ?>

The problem is that some scores are zero, so they’re not showing up. I understand that this is because 0 basically equals null, so the statement is false.

One solution I found and tried was this:

<?php if(get_field('my_field') !== false) : ?>
   <?php echo get_field('my_field'); ?>
<?php endif; ?>

However, this means that empty fields now show up too, which is not desirable since there are a lot of fields that are intended to be hidden if empty.

So, my question is, is there a way to phrase an if statement that allows for zeros, while still returning false if the field is empty? Please note that some scores aren’t purely numeric, with values like ‘6(1)’.

Advertisement

Answer

In order to check for empty strings you have to explicitly check them in your if condition.

<?php if(get_field('my_field') !== '') : ?>
   <?php echo get_field('my_field'); ?>
<?php endif; ?>

The reason is 0, null, empty string, empty array all evaluate to (but are not exactly) false, in case of a boolean check.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement