tags:

views:

92

answers:

5

If have a piece of code that gets some data from a sql database

$comms = $row['comments'] ; 

if ($comms != "") {
  $tooltip = "<b>Notes :</b> $comms </br>  ";  
}

What i want to do is display the result ONLY if there is something in the data. I am using the if statement to determine if $comms has any data in it but everything i try ("" " " 0 false) returns true. What is the value of nothing when returned (Although I have not included all the code I assure you that there is a value returned in $comms)

Any help would be great , thanks

A: 

Use the is_null ( mixed $var ) function:

if (!is_null($comms)){
  $tooltip = "<b>Notes :</b> $comms </br>  ";  
}
anthares
Shouldn't that be `!is_null`?
Select0r
True, thanks! :)
anthares
+2  A: 
is_null($foo)

A propos:

A variable is considered to be null if:

  • it has been assigned the constant NULL.
  • it has not been set to any value yet.
  • it has been unset().

http://php.net/manual/en/language.types.null.php

serhio
+7  A: 
if (!empty($comms)) {
  $tooltip = "<b>Notes :</b> $comms </br>  ";  
}

See http://php.net/manual/en/function.empty.php

If you are likely to get a value from the database that contains only whitespaces (I doubt it, but anyway), you will want to trim that variable first:

$comms = trim($comms);
if (!empty($comms)) {
  $tooltip = "<b>Notes :</b> $comms </br>  ";  
}

In response to @anthares comment (from the manual):

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)
karim79
If the comment is "0" this will be considered as empty, right ? Is this OK?
anthares
I know what the function returns. I mean that the OP probably wants to check if the values is NULL only ... and not "0" or "".
anthares
I'm under the impression that `!empty($a)` is true whenever `$a` would evaluate to true.
Matthew
Note that a string containing just whitespace is **not** considered empty
symcbean
@symcbean - yep, that's why I threw in the `trim` bit.
karim79
+1  A: 

Use the === and !== operators to check both value and type.

Ignacio Vazquez-Abrams
A: 

You could try this:

$comms = $row['comments'] ; 

if (!isEmpty($comms)) {
    $tooltip = "<b>Notes :</b> $comms </br>  ";  
}

Null-checking may also work (as anthares suggested)

Tilo Mitra
why downvoted? The chosen answer uses the same function.
Tilo Mitra
I've not downvoted you, but look the manual of isEmpty function, that you have used. http://php.net/manual/en/splheap.isempty.php
anthares
Sorry guys, actually meant empty(), not isEmpty()
Tilo Mitra