Welcome to Stackoverflow.
There are several ways to do what you want, I will show you a very simple one:
- You save a copy of the unsorted array
- Sort the array
- You compare the ordered array with the original copy: if they are equal it means that the array was ordered, if they are not equal it means that it was not
- If you are trying to print a message, you can create that message from a ternary operator that will compare the two arrays.
This is the code:
$array=array(1,2,3,6,8,9);
$notSorted=$array;
sort($array);
$msg=($array==$notSorted) ? "SÍ están ordenados" : "NO están ordenados";
echo $msg;
Exit:
SÍ están ordenados
If you try this array:
$array=array(1,2,3,6,8,4,9);
Exit:
NO están ordenados
If you want to save a varible Boolean of the comparison to use it in another site, you can do this:
$isSorted=($array==$notSorted);
Another possibility taking into account that you are not allowed to use sort
I'm still betting on simplicity. In this code:
- A boolean variable set to% default
TRUE
is created
- Each element of the array is read, saving in
$previo
a reference to the last element
- Compare if the current element is
<
than the previous element. If this condition is fulfilled it would mean that the array is not ordered.
- We set the boolean variable to
FALSE
and exit the loop with break
. (If you are not allowed to use break
you do a small trap , which is not really ... You remove break
and it will work the same! But for performance purposes, we put it because if that condition is met only once, we do not need to continue making comparisons).
- Finally we make the
if
based on the value of $isOrdered
... I do not even mention the ternary operators for now.
This is the code:
$array=array(0,1,2,3,6,7,8);
$isOrdered=TRUE;
$previo = null;
foreach($array as $item){
if($item<$previo){
$isOrdered=FALSE;
break;
}
$previo = $item;
}
if(!$isOrdered){
echo "No estan ordenats";
}
else{
echo "Estan ordenats";
}