note 65638 deleted from function.is-array by bjori
| From: | bjori@php.net | Date: | Thu, 04 May 2006 22:32:33 +0000 |
| Subject: | note 65638 deleted from function.is-array by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-110589@lists.php.net to get a copy of this message | ||
Note Submitter: Jared user at example dot com
Reason: bad code
----
This is a simple function to test whether an array is associative or not. Note this does NOT check
whether the variable passed to it is actually an array or not, and that it also may pass
'mixed' if there are numerical and associative array keys present. Also does not check for
multidimensional arrays.
<?php
function is_associative($arr)
{
$n = extract($arr);
$c = count($arr);
return ($n === $c ? true : (0 < $n ? 'mixed' : false));
}
?>
A test case of the above is_associative() function:
<?php
$test = Array('Array 0','Array 1','Array 2','Array
3','Array 4');
$set = extract($test);
echo('<div>Numerical: ' . count($test) . ' > ' . $set .
'</div>');
echo('<div>Is Associative: ' . is_associative($test) . '</div>');
foreach($test as $k => $v)
{
echo("<div style=\"padding-left: 20px;\">$k: $v</div>");
}
echo('<div>-----------------------</div>');
$test = Array('zero'=>'Array 0','one'=>'Array
1','two'=>'Array 2','three'=>'Array
3','four'=>'Array 4');
$set = extract($test);
echo('<div>Associative: ' . count($test) . ' > ' . $set .
'</div>');
echo('<div>Is Associative: ' . is_associative($test) . '</div>');
foreach($test as $k => $v)
{
echo("<div style=\"padding-left: 20px;\">$k: $v</div>");
}
echo('<div>-----------------------</div>');
$test = Array(0=>'Array 0','one'=>'Array
1','two'=>'Array 2','three'=>'Array
3','four'=>'Array 4');
$set = extract($test);
echo('<div>Mixed: ' . count($test) . ' > ' . $set .
'</div>');
echo('<div>Is Associative: ' . is_associative($test) . '</div>');
foreach($test as $k => $v)
{
echo("<div style=\"padding-left: 20px;\">$k: $v</div>");
}
?>
This would output:
Numerical: 5 > 0
Is Associative:
0: Array 0
1: Array 1
2: Array 2
3: Array 3
4: Array 4
-----------------------
Associative: 5 > 5
Is Associative: 1
zero: Array 0
one: Array 1
two: Array 2
three: Array 3
four: Array 4
-----------------------
Mixed: 5 > 4
Is Associative: mixed
0: Array 0
one: Array 1
two: Array 2
three: Array 3
four: Array 4