0

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 ?

14
  • 1
    Why are you multiplying a string? BTW everything multiplied by 1 is itself, isn't it? Commented Jun 21, 2016 at 11:03
  • 1
    @PhiterFernandes Oh, ok, sounds very dirty :) Commented Jun 21, 2016 at 11:05
  • 1
    If the aim is to convert it to a int, isn't it smarter to use (int) or some other designated method? Instead of multiplying it with 1? Commented Jun 21, 2016 at 11:08
  • 3
    From the docs: if you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically Commented Jun 21, 2016 at 11:10
  • 1
    @Albzi No, that will never match as you will be comparing a string to an integer and 2 !== '2'. Commented Jun 21, 2016 at 11:14

2 Answers 2

6

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');
}
Sign up to request clarification or add additional context in comments.

1 Comment

Gah can't believe I made that mistake! Definitely an off day for me.
0

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()

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.