PHP uses only associative arrays. To determine if an array could be an indexed array from 0
to size - 1
eg an array where elements have been pushed, or added using array[] = x
, the only method known is to check if all keys are from 0
to size - 1
.
(Note that an array could be built via the "associative" way (ie providing both keys and values), using incremental keys from 0
, and there is no way to determine that it was not built using the method given above (push or []
), since, anyway, that makes no difference)
$i = 0;
foreach (array_keys($array) as $key) {
if ($key !== $i) break; // Note the !== (not !=)
$i++;
}
if ($i == count($array)) {
// looks like array was built using indexing (see text above)
}
The final test $i == count($array)
, if true, indicates that all keys where numeric, starting from 0, incremented by 1 for each element, until the last element.