0

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

1
  • 1
    If you ever plan to use this project on a different server, you will probably want to change <? to <?php everywhere (that's not the standard open tag). Commented Sep 22, 2009 at 2:00

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 - I just use strlen to check, I didn't know about this function, as I never needed it. Thank you.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.