note 24482 rejected from function.is-array by victor
| From: | victor@php.net | Date: | Tue, 27 Aug 2002 06:38:32 +0000 |
| Subject: | note 24482 rejected from function.is-array by victor | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-35705@lists.php.net to get a copy of this message | ||
is_array contains a flaw
I'm using PHP 4.0.6-15 on a Red Hat Linux 7.2.
The flaw is: when use is_array to test an array of mixed elements of associative elements and
arrays, the associative elements will be considered as arrays (non-associative elements won't
pass the test). For example:
$as_ar = array(
array("me" => "5", "you"=>"6", "him"
=> "3", "her"=>"2", "us"=>"4", 12, 8),
"lone"=>9,
array("red"=>"3", "yellow"=>"4",
"green"=>"5", "cyan"=>"6",
"blue"=>"3", "purple"=>"3.2"),
array("east"=>"2", "west"=>"3",
"south"=>"4", "north"=>"5",
"up"=>"6", "down"=>"8",
"come"=>"10", "go"=>"1")
);
if (is_array($as_ar[1])){
echo "The second element is an array.";
}
This will print the message.
Now, if you believe the test result, you would do:
foreach ($as_ar[1] as $key => $value){
echo "The key is ".$key.";\tthe value is ".$value;
}
Obviously, PHP4 will complain about the element passed to foreach not being an array element.
Which one to trust? The is_array test or foreach complaint? For the sake of consistancy with the
name, anything but array should never pass is_array test.
To get the non-array element from the array could be tricky. But the following works fine:
$keyRing = array_keys ($as_ar);
$theKey = $keyRing[1];
$theValue = $as_ar[$theKey];
Hope this helps someone. I also suggest the code masters to perfect the is_array test. It might be
worth adding something like an is_associative_element test or something better. Thank you.