Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strcmp equivelant for integers (intcmp) in PHP

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;     }     .... } 
like image 380
Chase Wilson Avatar asked May 17 '10 20:05

Chase Wilson


People also ask

Will Comparison of string 15 and integer 15 works in PHP?

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.

What is strcmp () in PHP?

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.

How do I equate two strings in PHP?

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.

Is there any reason to use strcmp () for strings comparison?

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.


2 Answers

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.

like image 199
Nicolas Viennot Avatar answered Sep 22 '22 18:09

Nicolas Viennot


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

like image 33
nico Avatar answered Sep 22 '22 18:09

nico