'How can I Check in PHP if an assosiative array's Index is in Sequence or Not, and Raise an Exception if the IndexedArray is Not in sequence?

<?php
/*  
 1) Print all the elements from an Associative Array. Use key as Integer.
 2) Raise an Exception if the IndexedArray is Not in sequence.
*/
$arr = [1=>"Red",8=>"Blue",3=>"Black",6=>"Orange",5=>"Green"];
for($x=0; $x<=count($arr); $x++) //for loop to go thorugh each element by sequence
try{
    //what should I code here to check if the $arr is in sequence or not?
}catch(Exception $e){
      echo $e->getMessage();
}


Solution 1:[1]

One approach would be to compare a sorted vs unsorted list of array keys if you'r expecting an integer values

$arr = [1=>"Red",8=>"Blue",3=>"Black",6=>"Orange",5=>"Green"];
//$arr = [1=>"Red",3=>"Black",5=>"Green",6=>"Orange",8=>"Blue"];

function arrayKeysInSequence( $arr )
{
    $keys = $sorted = array_keys( $arr );
    asort($sorted);
    return $keys === $sorted;
}

arrayKeysInSequence( $arr );

Otherwise, you could track previous indexes, and return early when its greater than the current value

function arrayKeysInSequence( $arr )
{
    $prev = null;
    foreach( $arr as $index => $value )
    {
        if( $prev !== null and $prev > $index )
        {
            return false;
        }
        $prev = $index;
    }
    return true; 
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Scuzzy