1

I'm getting data from a MySQL database and trying to check if the column has data in it or not. Here's what one of the array elements looks like:

[2] => Array 
(   
        [p_name] => This is text
)

Now I have the following statement:

if($products[2]['p_name'] == 0)
      echo '$products[2][\'p_name\'] == 0';

The output is:

"$products[2]['p_name'] == 0"

Now, is it just me, or is that not make any sense whatsoever?

hakre
  • 193,403
  • 52
  • 435
  • 836
Nate
  • 26,164
  • 34
  • 130
  • 214

4 Answers4

2

A textual string casted to a number is always 0: (int) 'This is Text' is equal to 0.

You could just use the empty() function or is_numeric() and then your code:

if (empty($var))

(which check if $var is either "" (an empty string), 0 (0 as an integer), 0.0 (0 as a float), "0" (0 as a string), NULL, FALSE or array()).

or

if (is_numeric($var) && $var === 0))
entropid
  • 6,130
  • 5
  • 32
  • 45
  • Thanks! So how do I check if the cell is empty? – Nate Feb 04 '12 at 18:17
  • 1
    If it's always a string, use `=== ''`. Otherwise use `empty()`. Have a read about [type comparison](http://php.net/manual/en/types.comparisons.php). – cmbuckley Feb 04 '12 at 18:20
0

It's because you're comparing text to number. This will always compare 0 to 0

BartekR
  • 3,827
  • 3
  • 24
  • 33
0

If you're referring to why "This is text" == 0, it's because PHP is loosely typed, and when you compare the string with an integer, the string is casted to 0.

This is likely not the desired behaviour, so you will need to use the equality operator, for example,

`"This is text" == 0` // True
`"This is text" === 0` // False

Demo

nickb
  • 59,313
  • 13
  • 108
  • 143
-1
if (isset($products[2]['p_name']) && !empty($products[2]['p_name']) ) 
{
    //your code
}
PHP Connect
  • 539
  • 2
  • 7
  • 24