0

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

9
  • 3
    How do you know it's returning true, is $num equal to 10? Commented May 29, 2012 at 22:35
  • @rudi_visser: I'm runnign the code in Debug mode. So, I can see that $num is increasing in each iteration. Also, I can see that cursor goes inside the loop. Commented May 29, 2012 at 22:36
  • 1
    There is no such thing as "Debug mode" in the context of the real PHP parser. What is the actual output of PHP when executing directly? Ignore Zend Studio for now. Commented May 29, 2012 at 22:36
  • 1
    Read up on how == and === work in PHP. Commented May 29, 2012 at 22:38
  • 1
    @rudi_visser: it is a debug mode, when you may doing everything debug mode is implying Commented May 29, 2012 at 22:41

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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)

Comments

-2

any string compared to 0 it's true

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.