Voting

: seven plus one?
(Example: nine)

The Note You're Voting On

angelo [at] mandato <dot> com
18 years ago
The is_associative_array() and is_sequential_array() functions posted by 'rjg4013 at rit dot edu' are not accurate.

The functions fail to recognize indexes that are not in sequence or in order. For example, array(0=>'a', 2=>'b', 1=>'c') and array(0=>'a', 3=>'b', 5=>'c') would be considered as sequential arrays. A true sequential array would be in consecutive order with no gaps in the indices.

The following solution utilizes the array_merge properties. If only one array is given and the array is numerically indexed, the keys get re-indexed in a continuous way. The result must match the array passed to it in order to truly be a numerically indexed (sequential) array. Otherwise it can be assumed to be an associative array (something unobtainable in languages such as C).

The following functions will work for PHP >= 4.

<?php
function is_sequential_array($var)
{
return (
array_merge($var) === $var && is_numeric( implode( array_keys( $var ) ) ) );
}

function
is_assoc_array($var)
{
return (
array_merge($var) !== $var || !is_numeric( implode( array_keys( $var ) ) ) );
}
?>

If you are not concerned about the actual order of the indices, you can change the comparison to == and != respectively.

<< Back to user notes page

To Top