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
-
I think it's because the variable is NULL if it's not definedKamil Sindi– Kamil Sindi2011年11月07日 22:11:28 +00:00Commented Nov 7, 2011 at 22:11
5 Answers 5
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/>";
6 Comments
"*" . $var . "*" method again ;)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).
Comments
Do it with if (isset($contactId)) {}.
3 Comments
false, $contactId is not set so you should get a notice telling you so. Make sure your php setting display_errors is set to 1, and that error_reporting is set to -1You 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: https://www.php.net/manual/en/language.types.null.php
1 Comment
In future, use if(!empty($str)) { echo "string is not empty"}.
2 Comments
$contactId="0";."" (an empty string), 0 (0 as an integer), 0.0 (0 as a float), "0" (0 as a string), NULL, FALSE, array() (an empty array), var $var; (a variable declared, but without a value in a class), for your case - $contactId, if it is numeric, then just check it like is_numeric