5

From the question Type-juggling and (strict) greater/lesser-than comparisons in PHP

I know PHP interpret strings as numbers whenever it can.

"10" < "1a"  => 10 less than 1      expecting  false 
"1a" < "2"   => 1 less than 2       expecting  true
"10" > "2"   => 10 greater than 2   expecting  true

But in the case of "10" < "1a" php returns true.

I am not understanding the concept please help me to clarify it.

Edit:

But when I add "10" + "1a" it returns 11 that means php interprets "10" as 10 and "1a" as 1. Is that correct?

5 Answers 5

6

A comes after 9. You can see this in this string, sorted from low to high.

0123456789abcdefghijklmnopqrstuvwxyz

So 10 is lower than 1a.

1
  • Nice and simple. Thanks
    – Kiren S
    Nov 1, 2013 at 10:00
4

It's easy 1a is not numeric. So PHP compares string(2)"10" against string(2)"1a" and numbers are before alpha characters in the most text encoding tables (have a look at the ASCII or UTF-8 character tables).

So 1 of 10 is equals 1of 1a and 0 of 10 is lower than a of 1a. That results in 10 is lower than 1a.

2
  • I got it. But when adding it is another result. Please see my edit
    – Kiren S
    Nov 1, 2013 at 9:54
  • Mathematic operations are another shoe that's true cause PHP can not add two strings but compare two strings. This is why PHP propably extract the numbers out of 1a if you try to add it. But you should never ever do something like that! Even if PHP don't treat it with an error ;-). That's how you would add a pear in a bucket full of apples. Nov 1, 2013 at 9:56
3

If you want to be sure, that you comparing numbers, put (type) before variable:

(int)"10" < (int)"1a"
(int)"1a" < (int)"2"
(int)"10" > (int)"2"
0

Maybe you first need to use regular expressions?

For example:

$str = '1a';
$str = preg_replace ("/[^0-9\s]/","", $str);
var_dump((int)$str); // int 1
-1

Read at this link to get what happens when comparing value of two different data types.

Use type juggling to compare values of two different data type.

(int)"10" < (int)"1a"  result will be false
(int)"1a" < (int)"2"  result will be true
1
  • That's not type juggling, that's type casting. Check the page you linked to, it's under a different heading. Type juggling is what PHP does automatically, type casting is when you tell it what to do explicitly using e.g. (int).
    – Niall
    Aug 29, 2017 at 11:48

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.