PHP
Check if a PHP Array is Purely Numerically Indexed
Validate if a PHP array is a purely numerically indexed list with consecutive keys starting from zero, ensuring its structure matches expectations for lists.
<?php
function is_sequential_array(array $array): bool {
if (empty($array)) {
return true; // An empty array can be considered sequential
}
return array_keys($array) === range(0, count($array) - 1);
}
$sequentialArray = ['apple', 'banana', 'cherry'];
$associativeArray = ['fruit1' => 'apple', 'fruit2' => 'banana'];
$mixedArray = [0 => 'apple', 'fruit2' => 'banana'];
$nonZeroStartIndex = [1 => 'apple', 2 => 'banana'];
$sparseArray = [0 => 'apple', 2 => 'cherry'];
$emptyArray = [];
echo "Sequential: " . (is_sequential_array($sequentialArray) ? 'true' : 'false') . "
";
echo "Associative: " . (is_sequential_array($associativeArray) ? 'true' : 'false') . "
";
echo "Mixed: " . (is_sequential_array($mixedArray) ? 'true' : 'false') . "
";
echo "Non-zero start: " . (is_sequential_array($nonZeroStartIndex) ? 'true' : 'false') . "
";
echo "Sparse: " . (is_sequential_array($sparseArray) ? 'true' : 'false') . "
";
echo "Empty: " . (is_sequential_array($emptyArray) ? 'true' : 'false') . "
";
// Expected Output:
// Sequential: true
// Associative: false
// Mixed: false
// Non-zero start: false
// Sparse: false
// Empty: true
?>
How it works: The `is_sequential_array` function checks if an array is purely numerically indexed, with keys starting from 0 and incrementing consecutively without gaps. It achieves this by comparing the array's keys with a `range` of expected keys. This is crucial for validating data structures, especially when expecting a strict list format from external input or for internal processing where key type and order matter.