2

this is code:

$s = 0;
$d = "dd";

if ($s == $d) {
    var_dump($s);
    die(var_dump($d));
}

result is:

int 0

string 'dd' (length=2)

Please explain why.

why ($s == $d) results as true?

Of course, if === is used it will results as false but why this situation requires ===? Shouldn't it be returned false in both situations?

1
  • 4
    Not sure why there are downvotes on this question. It might be simple if you know the answer, but is shows someone who is trying to understand their code and getting to the nitty-gritty of how the language works. +1 from me. Commented Sep 14, 2012 at 9:15

6 Answers 6

4

Because (int)$d equals with 0 and 0=0

you must use strict comparison === for different character tyes (string) with (int)

Your $d is automatically converted to (int) to have something to compare.

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

3 Comments

You really have your finger on the pulse tonight :) +1
Tonight, it's freakin' 12PM here:)
You should move to a place that is further up the timezone, it's after seven PM Friday night here. (Awww, that just made me realize that I am a really sad bugger - spending Friday night answering programming questions)
4

When you compare a number to a string, the string is first type juggled into a number. In this case, dd ends up being juggled into 0 which means that it equates to true (0==0).

When you change the code to:

 <?php 
 $s = 1;
 $d = "dd";
 if ($s == $d)
 {
    var_dump($s);
    die(var_dump($d));
 }
 ?>

You will find that it doesn't pass the if statement at all.

You can more details by reading up on comparison operators and type juggling.

1 Comment

@MihaiIorga Yeah, but I made a grand entrance! swings cape !
2

The string "dd" is converted to int, and thus 0.

Another example :

if ( "3kids" == 3 )
{
      return true;
}

And yes, this returns true because "3kids" is converted to 3.

=== does NOT auto convert the items to the same type.

Also : 0 == false is correct, but 0 === false is not.

See : http://php.net/manual/en/language.types.type-juggling.php

Comments

2

The string will try to parsed into a number, returns 0 if it is not in right number format.

Comments

2

As seen in the php website : http://php.net/manual/en/language.operators.comparison.php

var_dump(0 == "a"); // 0 == 0 -> true

Comments

2

In PHP, == should be pronounce "Probably Equals".

When comparing with ==, PHP will juggle the file-types to try and find a match.

A string with no numbers in it, is evaluated to 0 when evaluated as an int.

Therefore they're equals.

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.