Gusgus
Gusgus

Reputation: 353

PHP: If statement returns True instead of False

I have an array called as myArr. It contains strings and integers, e.g.

0  st ts 0  0
st 0  0  0  0

For debugging the php script, I'm using Zend Studio. The debug window says that a cell [0][0] contains int 0. BUT the problem is that IF statement returns TRUE.

        for ($i = 0; $i < $rows; $i++) {
          for ($j = 0; $j < $cols; $j++) {
            if ($myArr[$i][$j] == 'ts' || $myArr[$i][$j] == 'st') {
                $num++;
            }
          }
        }

UPDATE: I'm running the code in Debug mode in Zend Studio. So, I can see that $num is increasing in each iteration. Also, I can see that cursor goes inside the loop

Upvotes: 0

Views: 222

Answers (3)

Ahmed Jolani
Ahmed Jolani

Reputation: 3092

When a string is compared to an integer, the string will be converted to an integer automatically and in your case the string has no digits so it will be evaluated to zero leading to satisfy the equality, you have two options:

if ('0' == 'tr')

OR

if (0 === 'tr')

were the === means check for the value and type.

I also found this helpful for you from the PHP manual:

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero)

Upvotes: 5

Dan Dumitriu
Dan Dumitriu

Reputation: 226

any string compared to 0 it's true

Upvotes: -2

nickb
nickb

Reputation: 59709

Because 0 == 'ts' is true. You need to use the equality comparison ===. Otherwise, PHP's type juggling causes this statement to evaluate to true.

See this demo to show why the if statement is evaluating to true.

Upvotes: 8

Related Questions