Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare string "numerically first"

I want to compare two string "numerically". I mean like 2C is less than 11A. I tried this and it's not working:

if("2A" < "11A"){
    echo "First corect";
}

if(strcmp("2A", "11A") < 0){
    echo "Last corect";
}

echo "Tests completed";
like image 741
Octavian Avatar asked Aug 23 '26 11:08

Octavian


2 Answers

You are looking for strnatcmp (or its case-insensitive sibling, strnatcasecmp).

This will compare the numeric parts of your input as numbers (placing "2whatever" before "11whatever") and the textual parts as text (placing "2a" before "2b").

like image 161
Jon Avatar answered Aug 26 '26 03:08

Jon


Try it like this:

if((int) '2A' < (int) '11A'){
    echo "First correct";
}

You can also take a look at: http://php.net/manual/en/function.intval.php

like image 40
Anyone Avatar answered Aug 26 '26 03:08

Anyone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!