1

I'm declaring a var $t and assigning it a value of 0. I then reassign $t a new value of test. It then appears that $t is both 0 AND test. Here's the code:

$t = 0;
$t = "test";

if($t == 0 && $t == "test"){
    echo "unexpected";
}else{
    echo "expected";
}

The output is:

"unexpected"

Can someone please explain what is going on here? Is $t really two different values (0 and test) at the same time or am I missing something?

2
  • I'm not sure why, but if you make the code just: $t = 'test'; if($t == 0) {echo 'yes';} it echos yes. So apparently the string evaluates to the same value as 0. Commented Feb 2, 2015 at 6:01
  • 1
    Visit: stackoverflow.com/questions/672040/… Commented Feb 2, 2015 at 6:02

4 Answers 4

4

This "strange" behaviour results in because of PHP's type juggling. Since you're using loose comparison == to compare to an integer 0 the string test is being converted to an integer, which results in conversion to 0. See the Loose comparison == table. There in the row with the string php you'll see that it equals to the integer 0, which applies to all strings.
You should be using strict (type) comparison operators, i.e. ===.

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

Comments

0

You're not appending or concatenating so it shouldn't be. Try the identical comparison operator instead.

if($t === 0 && $t === "test"){
   ....
}

Comments

0

PHP MANUAL STATES:

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). Valid numeric data is an >optional sign, followed by one or more digits >(optionally containing a decimal point), >followed by an optional exponent. The >exponent is an 'e' or 'E' followed by one or >more digits.

http://il.php.net/manual/en/language.types.string.php#language.types.string.conversion

So $t == 0 is true. You have to use strict comparison ===

Comments

0

Hey buddy use "===" operator for your comparison.

In php we can assign any value to a simple variable, it holds numeric, float, character, string, etc.

So always use "===" operator for unique or same value matching.

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.