So we got this function in PHP
strcmp(string $1,string $2) // returns -1,0, or 1;
We Do not however, have an intcmp(); So i created one:
function intcmp($a,$b) { if((int)$a == (int)$b)return 0; if((int)$a > (int)$b)return 1; if((int)$a < (int)$b)return -1; }
This just feels dirty. What do you all think?
this is part of a class to sort Javascripts by an ordering value passed in.
class JS { // array('order'=>0,'path'=>'/js/somefile.js','attr'=>array()); public $javascripts = array(); ... public function __toString() { uasort($this->javascripts,array($this,'sortScripts')); return $this->render(); } private function sortScripts($a,$b) { if((int)$a['order'] == (int)$b['order']) return 0; if((int)$a['order'] > (int)$b['order']) return 1; if((int)$a['order'] < (int)$b['order']) return -1; } .... }
The class doesn't provide a method to convert this type to a number, so it's not able to perform the comparison. However, it appears that this type has a method to convert to string. But PHP won't do a double conversion when performing the comparison.
PHP | strcmp() FunctionThis function compares two strings and tells us that whether the first string is greater or smaller than the second string or equals to the second string.
Answer: Use the PHP strcmp() function You can use the PHP strcmp() function to easily compare two strings. This function takes two strings str1 and str2 as parameters. The strcmp() function returns < 0 if str1 is less than str2 ; returns > 0 if str1 is greater than str2 , and 0 if they are equal.
You can use strcmp() if you wish to order/compare strings lexicographically. If you just wish to check for equality then == is just fine. Like in usort. In fact, it's pretty much made for sorting.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With