Php test empty string

I have some php code that I don’t understand why it acts as it is. I have a variable called contactId that I want to check if it is empty. However, even if it is empty, it is true. The code is below. Thanks in advance.

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

returned to the screen:

**

Contact with us

+7
source share
5 answers

If you want to know exactly what your string is, just use var_dump() , for example:

 var_dump($contactId) 

instead

 print "*".$contactId."*<br/>"; 
+9
source

A few 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 often used the last of two solutions, because there were cases when I would expect the variable to have the value 0, which is valid in some contexts. For example, if I have a website for finding drinks and you want to indicate whether the ingredient is non-alcoholic, I would set it to 0 (i.e., IngredientId = 7, Alcoholic = 0).

+2
source

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

+1
source

You probably want:

 if (strlen($contactId)) 

You need to know the difference between '' and null , as well as 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

0
source

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

0
source

All Articles