views:

399

answers:

2

I'm trying to just write a simple PHP if statement that checks if a custom field has anything entered into or if it has been left blank.

when it is blank it is meant to not print anything to the page, if something is set in the custom field then it should create a li element with an a tag inside of it.

here is my code so far:

<ul class="externalLinks">
<? $emptycheck = get('linkname',2,1,0);

if (isset($emptycheck)){ ?>
   <li><a href="<? echo get('targethref',2,1,0); ?>"><? echo get('linkname',2,1,0);?></a></li>
<? } else { '' } ?>

<li><a href="<? echo get('PDFdownload'); ?>">Download a PDF of this project</a></li>
</ul>

The custom fields in this case are set by the wordpress admin (through the flutter plugin). The issue I am having is simply that if the custom fields are left blank an empty

<li><a></a></li>

is created.

get('linkname',2,1,0) returns the field content obviously (this part works).

Any ideas would be much appreciated.

Thanks, Jannis

+5  A: 

Just because a variable is empty doesn't mean it's not isset().

You want to check if it's empty() or not.

$whatever = get('whatever',2,1,0)
if (! empty($whatever)){
//output your stuff
}

To be clear: isset() will just tell you if the variable name exists in the symbol table. empty() will return true when a variable is empty.

According to the documentation:

The following things are considered to be empty:

  • "" (an empty string)
  • 0 (0 as an integer)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • var $var; (a variable declared, but without a value in a class)

Edited: empty() is kind of special, and operates only on a regular variable. You can't test an expression (for instance, the return value of a function) with empty(). This is clearly documented on the manual page.

timdev
+1 - I just use strlen to check, I didn't know about this function, as I never needed it. Thank you.
James Black
Thank you, this works perfectly.
Jannis
@ gumbo: you're right. Editing...
timdev
+1  A: 

You're setting $emptycheck regardless, if the return value is falsy you might want

if ( $emptycheck ) {
} else {
}

Otherwise it will always evaluate to true. Or flip the logic around with a negation operator ( ! ) if it's the other way around.

meder