I would like to display some html code if a variable is not empty, else I would like to display nothing.
I've tried this code but doesn't work:
<?php
$web = the_field('website');
if (isset($web)) {
?>
<span class="field-label">Website: </span><a href="http://<?php the_field('website'); ?>" target="_blank"><?php the_field('website'); ?></a>
<?php
} else {
echo "Niente";
}
?>
isset
will return true even if the variable is "".isset
returns false only if a variable is null. What you should be doing:This will check that he variable is not empty.
Hope this helps
i hope this will work too, try using"is_null"
http://php.net/manual/en/function.is-null.php
hope that suits you..
You're using
isset
, whatisset
does is check if the variable is set ('exists') and is notNULL
. What you're looking for isempty
, which checks if a variable is empty or not, even if it's set. To check what is empty and what is not take a look at:http://php.net/manual/en/function.empty.php
Also check http://php.net/manual/en/function.isset.php for what
isset
does exactly, so you understand why it doesn't do what you expect it to do.Focusing on the error suppression part, if the variable is an array where a key being accessed may or may not be defined:
if($web['status'])
would produce:if(isset($web['status']) && $web['status'])
(2nd condition is not tested if the 1st one isFALSE
) ORif(!empty($web['status']))
.However, as deceze♦ pointed out, a truthy value of a defined variable makes
!empty
redundant, but you still need to remember that PHP assumes the following examples asFALSE
:null
''
or""
0.0
0
'0'
or"0"
'0' + 0 + !3
So if zero is a meaningful status that you want to detect, you should actually use string and numeric comparisons:
Error free and zero detection:
The generic condition (
$web['status']
) should be left at the end of the entire statement.Simply use
if ($web)
. This istrue
if the variable has any truthy value.You don't need
isset
orempty
since you know the variable exists, since you have just set it in the previous line.Your problem is in your use of
the_field()
, which is for Advanced Custom Fields, a wordpress plugin.If you want to use a field in a variable you have to use this:
$web = get_field('website');
.