I have a small task in php. I have a simple array.
Array
(
[0] => 50
[1] => 100
[2] => 150
)
Is there a php built in function which i can use so that it can return true or false, accordingly if array is already sorted or not, Or any other php script for this, no loops. I know it is easy with loops and conditions.
You can compare your input array with sorted one if they are equal.
$input = array(50, 100, 150);
$sorted = array_values($input);
sort($sorted);
if ( $input === $sorted ) {
// input array was already sorted
}
function arraySorted($array) {
$a = $array;
$b = $array;
sort($b);
if ($a == $b){
return true;
} else {
return false;
}
}
//test for [0],[3],[2]
$input = array(0 => 250,
3 => 100,
2 => 150);
var_dump($input);
echo "<br />";
//array(3) { [0]=> int(250) [3]=> int(100) [2]=> int(150) }
var_dump(arraySorted($input));
echo "<br />";
//bool(false)
//test for [0],[1],[2]
$input = array(0 => 250,
1 => 100,
2 => 150);
var_dump($input);
echo "<br />";
//array(3) { [0]=> int(250) [1]=> int(100) [2]=> int(150) }
var_dump(arraySorted($input));
echo "<br />";
//bool(false)
//test for [0],[3],[2] and asc values
$input = array(0 => 50,
1 => 100,
2 => 150);
var_dump($input);
echo "<br />";
//array(3) { [0]=> int(50) [1]=> int(100) [2]=> int(150) }
var_dump(arraySorted($input));
echo "<br />";
//bool(true)
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