Yet another safer, faster way of detecting whether an array is associative.
The principle is: using array reduction on the keys, we verify that each key is numeric and is equal to its rank.
Beware: integer keys that are not in sequence, or are negative, or with "holes", still make an associative array.
<?php
function isNotAssocArray($arr)
{
return (0 !== array_reduce(
array_keys($arr),
create_function('$a, $b', 'return ($b === $a ? $a + 1 : 0);'),
0
)
);
}
?>
Of course, it is still faster if the callback for array_reduce is not an anonymous function:
<?php
function callbackReduceNotArray($a, $b)
{
return ($b === $a ? $a + 1 : 0);
}
function isVector($arr)
{
return (0 !== array_reduce(
array_keys($arr),
'callbackReduceNotArray',
0
)
);
}
?>