Home » Php » Php test empty string

Php test empty string

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have a bit of php code that I’m not understanding why it is acting as it is. I have a variable called contactId that I want to test to see if it is empty. However even if it is empty it evaluates to true. Code is below. Thanks in advance.

print "*".$contactId."*<br/>";
if($contactId != '')
{
    //queryContact($contactId);
    print "Contact Present<br/>";
}

result returned to screen is:

**

Contact Present

How to&Answers:

If you want to see exactly what your string is, simply use var_dump(), like this, for instance:

var_dump($contactId)

instead of

print "*".$contactId."*<br/>";

Answer:

Couple of things you can try:

if (!empty($contactId)) {
    // I have a contact Id
}

// Or

if (strlen($contactId) > 0) {
    // I have a contact id
}

In my experience I have often used the latter of the two solutions because there have been instances where I would expect a variable to have the value of 0, which is valid in some contexts. For example, if I have a drink search site and want to indicate if an ingredient is non-alcoholic I would assign it a value of 0 (i.e. IngredientId = 7, Alcoholic = 0).

Answer:

Do it with if (isset($contactId)) {}.

Answer:

You likely want:

if (strlen($contactId))

You’ll want to learn the difference between '' and null, and between == and ===. See here: http://php.net/manual/en/language.operators.comparison.php

and here: http://us3.php.net/manual/en/language.types.null.php

Answer:

In future, use if(!empty($str)) { echo "string is not empty"}.