strcmp equivelant for integers (intcmp) in PHP

Purely as some additional information, there has been an accepted RFC for this (https://wiki.php.net/rfc/combined-comparison-operator).

So, the comparison function would be along the lines of ...

<?php
$data = [...];
usort($data, function($left, $right){ return $left <=> $right; });
?>

A few really nice feature here is that the comparison is done in exactly the same way as all other comparisons. So type juggling will happen as expected.

As yet, there is no magic __forCompare() like method to allow an object to expose a comparison value. The current proposal (a different RFC) is to have each object be injected into every other object during the comparison so that it does the comparison - something which just seems odd to me - potential opportunity for recursion and stack overflow ... ! I would have thought either injecting the type of object for comparison (allowing an object the ability to represent appropriate values depending upon the type of comparison) or a blind request for a value that the object can serve up for comparison, would have been a safer solution.

Not yet integrated into PHP-NG (PHP 7 at the moment), but hopefully will be soon.


You could use

function intcmp($a,$b)
    {
    return ($a-$b) ? ($a-$b)/abs($a-$b) : 0;
    }

Although I don't see the point in using this function at all


why reinventing the wheel? http://php.net/manual/en/function.strnatcmp.php

echo strnatcmp(1, 2) . PHP_EOL; // -1
echo strnatcmp(10, 2) . PHP_EOL; // 1
echo strnatcmp(10.5, 2) . PHP_EOL; // 1 - work with float numbers
echo strnatcmp(1, -2) . PHP_EOL; // 1 - work with negative numbers

Test it here: https://3v4l.org/pSANR


Sort your data with:

function sortScripts($a, $b)
{
    return $a['order'] - $b['order'];
}

Use $b-$a if you want the reversed order.

If the numbers in question exceed PHP's integer range, return ($a < $b) ? -1 : (($a > $b) ? 1 : 0) is more robust.