Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing numeric strings

Tags:

php

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?

like image 665
Kiren S Avatar asked Nov 01 '13 09:11

Kiren S


3 Answers

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

0123456789abcdefghijklmnopqrstuvwxyz

So 10 is lower than 1a.

like image 80
Steyx Avatar answered Sep 24 '22 20:09

Steyx


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.

like image 44
TiMESPLiNTER Avatar answered Sep 20 '22 20:09

TiMESPLiNTER


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"
like image 33
KiraLT Avatar answered Sep 23 '22 20:09

KiraLT