Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Check if an array is already sorted in php

Tags:

arrays

php

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.

like image 767
Muhammad Raheel Avatar asked Dec 04 '22 00:12

Muhammad Raheel


2 Answers

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
}
like image 114
hsz Avatar answered Dec 22 '22 06:12

hsz


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)
like image 39
primetwig Avatar answered Dec 22 '22 07:12

primetwig