Peon
Peon

Reputation: 8020

If returning wrong result when comparing integer with string

Not sure if I'm not seeing something or what, but I have a simple id validation

$id = '2s2';

var_dump($id);
var_dump($id*1);
if ($id != ($id*1) || $id <= 0) {
    die('wrong id');
}
die('here?');

The result:

string '2s2' (length=3)
int 2
here?

It checks if id is the same as id multiplied by 1 or if the value is zero or lower. Since, the value of $id = '2s2; it is not the same ( as can be seen in the dump ).

Why is this not echoing wrong id ?

Upvotes: 0

Views: 253

Answers (2)

Ruslan Bes
Ruslan Bes

Reputation: 2735

When you compare two variables of different types (and do some other operations) PHP does an operation called Type Juggling. Basically it tries to convert both operands to the same type before operating on them.

In this case somewhat counter-intuitively PHP converts both operands to integers. The rule of converting a string to integer is basically "take chars from the beginning of a string until non-number found and discard the rest".

So left-hand $id is indeed "2s2" and is stripped from the non-integer part to "2" and then compared to the right operand. The right operand ($id*1) essentially passes through the same process - in mathematical context PHP is forced to treat your string as if it is integer.

You can use strict comparison operator if ($id !== ($id*1)) - that way you tell PHP you don't want type-juggling involved and the result would be as you have expected.

Also there is much easier way to test if $id is integer: is_int() and is_numeric()

Upvotes: 0

Marc Compte
Marc Compte

Reputation: 4819

I'm guessing you multiply it by 1 to see if the $id is numeric. In that case you could simply:

if (!is_numeric($id) || $id <= 0) {
    die('wrong id');
}

Upvotes: 6

Related Questions