开发者

PHP value of nothing?

开发者 https://www.devze.com 2022-12-22 15:07 出处:网络
If have a piece of code that gets some data from a sql database $comms = $row[\'comments\'] ; if ($comms != \"\") {

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 ret开发者_开发知识库urned (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


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)


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


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


Use the is_null ( mixed $var ) function:

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


You could try this:

$comms = $row['comments'] ; 

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

Null-checking may also work (as anthares suggested)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号