note 77428 added to function.is-array
| From: | gabriel at bumpt dot nothing-here dot net | Date: | Wed, 29 Aug 2007 15:34:06 +0000 |
| Subject: | note 77428 added to function.is-array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-129877@lists.php.net to get a copy of this message | ||
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
/**
* @param array $arr
* @returns boolean
*/
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
)
);
}
?>
----
Server IP: 69.147.83.197
Probable Submitter: 207.45.248.18
----
Manual Page -- http://www.php.net/manual/en/function.is-array.php
Edit -- https://master.php.net/note/edit/77428
Del: integrated -- https://master.php.net/note/delete/77428/integrated
Del: useless -- https://master.php.net/note/delete/77428/useless
Del: bad code -- https://master.php.net/note/delete/77428/bad+code
Del: spam -- https://master.php.net/note/delete/77428/spam
Del: non-english -- https://master.php.net/note/delete/77428/non-english
Del: in docs -- https://master.php.net/note/delete/77428/in+docs
Del: other reasons-- https://master.php.net/note/delete/77428
Reject -- https://master.php.net/note/reject/77428
Search -- https://master.php.net/manage/user-notes.php