I am looking for a method to check if values of a numeric 2D PHP array are in
incereasing , descending , or mixed order.
Example:
array( 1, 2, 3, 4 ) // This is an incereasing numeric array
array( 4, 3, 2, 1 ) // This is a descending numeric array
array( 1, 3, 2, 4 ) // This is a mixed numeric array
How could I check it? ( i am looking for a fast method, it needs to run qickly )
I think, if you are looking for quick solution (i.e. works quick), you'll have to work with your data array like:
function getOrder($rgData)
{
if(!count($rgData) || count($rgData)==1)
{
return null;
}
$sCurrent = (string)array_shift($rgData);
$iOrder = current($rgData)>$sCurrent?1:-1;
foreach($rgData as $mValue)
{
if(($sCurrent>(string)$mValue && $iOrder== 1) ||
($sCurrent<(string)$mValue && $iOrder==-1))
{
return 0;
}
$sCurrent = (string)$mValue;
}
return $iOrder;
}
this will return 1,0 and -1 for corresponding ascending, mixed and descending order. Note, that all values will be treated and compared as strings. This method is more useful since it have O(N)
complexity (at worst case) while using sort()
function will result in O(N log(N))
complexity (at best case)
Assuming your variable is called $array
this might start in the right direction:
$tempArray=sort($array);
if($array==$tempArray)
{
// Array is in acsending order
}
$tempArray=arsort($array);
if($array==$tempArray)
{
// Array is in desending order
}
If neither of these match, it's mixed.
Edit: Thanks to Alma Do Mundo, Corrected code.