note 86407 modified in function.is-array by danbrown
| From: | danbrown@php.net | Date: | Thu, 16 Oct 2008 22:44:15 +0000 |
| Subject: | note 86407 modified in function.is-array by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-145441@lists.php.net to get a copy of this message | ||
alex frase's example is fast but elanthis at awesomeplay dot com's example is faster and
Ilgar's modification of alex's code is faulty (the part " || $_array[$k] !==
$v"). Also, Ilgar's suggestion of giving a false return value when the variable isnt an
array is not suitable in my opinion and i think checking if the array is empty would also be a
suitable check before the rest of the code runs.
So here's the modified (is_vector) version
<?php
function is_vector( &$array ) {
if ( !is_array($array) || empty($array) ) {
return -1;
}
$next = 0;
foreach ( $array as $k => $v ) {
if ( $k !== $next ) return true;
$next++;
}
return false;
}
?>
and the modified (alex's is_assoc) version
<?php
function is_assoc($_array) {
if ( !is_array($_array) || empty($array) ) {
return -1;
}
foreach (array_keys($_array) as $k => $v) {
if ($k !== $v) {
return true;
}
}
return false;
}
?>
--was--
alex frase's example is fast but elanthis at awesomeplay dot com's example is faster and
Ilgar's modification of alex's code is faulty (the part " || $_array[$k] !==
$v"). Also, Ilgar's suggestion of giving a false return value when the variable isnt an
array is not suitable in my opinion and i think checking if the array is empty would also be a
suitable check before the rest of the code runs.
So here's the modified (is_vector) version
function is_assoc( &$array ) {
if ( !is_array($array) || empty($array) ) {
return -1;
}
$next = 0;
foreach ( $array as $k => $v ) {
if ( $k !== $next ) return true;
$next++;
}
return false;
}
and the modified (alex's is_assoc) version
function is_assoc($_array) {
if ( !is_array($_array) || empty($array) ) {
return -1;
}
foreach (array_keys($_array) as $k => $v) {
if ($k !== $v) {
return true;
}
}
return false;
}
http://php.net/manual/en/function.is-array.php