Octavian
Octavian

Reputation: 4579

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";

Upvotes: 2

Views: 149

Answers (4)

Paleogeek
Paleogeek

Reputation: 1

Write a function that:

  1. Tokenizes each String into a List <Object> where each object can be a String or Integer with the Integers being created from a contiguous string of digits between non-digits, the Strings being contiguous non-digits between any 2 digits.
  2. In a loop compare the two Lists element by element. If the type of the objects doesn't match (i.e. comparing an Integer to a String) make the less/greater decision on which you want to sort as smaller, letters or digits. If they match just do a less than, equals, greater than comparison.
  3. If the two Nth elements in the list are equal, go on to compare the N+1th elements, otherwise return t/f based on the integer to integer or string to string comparison.

Upvotes: 0

ankit
ankit

Reputation: 455

if(intval(0x2A) < intval(0x11A)){
    echo "First corect";
}
else
{
    echo "Tests incompleted";
}

try this code

Upvotes: 0

Jon
Jon

Reputation: 437366

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").

Upvotes: 7

Anyone
Anyone

Reputation: 2835

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

Upvotes: 2

Related Questions