DEV Community

Discussion on: Beware of PHP’s strcmp() function when sorting

Collapse
 
leohajder profile image
Leo Hajder • Edited

strcmp works as intended. The only thing to beware here is using strcmp or equivalents to compare numeric values. This is the case in most, if not all languages, not only PHP.
This is one of those things. Always dump and test. Never assume.

The clue that could have saved you sooner is this, IMHO:
You need to compare two values. Whether those are primitive values or not, the comparison always comes down to comparing two primitive type values of the same type, right? It's easy to compare primitive types. Should you cast two numeric values to string when comparing? No, right? Ok, what does strcmp do? It compares two string values. Do you have string values, or something else? Is strcmp the right choice? No, right? :)

Collapse
 
wnbsmart profile image
Maroje Macola

Hi Leo, sorry for the late response and thanks for your comment.

Everything works as intended, if you know what is intended :)
This is where research & testing comes in, and if you take a look at my post again (where I honestly admitted my mistake), you might see that that's exactly the point of the post.

Cheers!