note 124039 added to function.is-array

From: Date: Sun, 14 Jul 2019 18:54:00 +0000
Subject: note 124039 added to function.is-array
Groups: php.notes 
Request: Send a blank email to php-notes+get-211603@lists.php.net to get a copy of this message
The next post is not correct because has problems with blank array index: https://www.php.net/manual/es/function.is-array.php#89332 The next code use the above link php code <?php function is_assoc($var) { return is_array($var) && array_diff_key($var,array_keys(array_keys($var))); } function test($var) { echo is_assoc($var) ? "I'm an assoc array.\n" : "I'm not an assoc array.\n"; } // an assoc array $a = array("a"=>"aaa","b"=>1,"c"=>true); test($a); // maybe assoc array? $b = array(0 => "aaa", 1 => 1, 3 => true); // Index 2 not exist test($b); ?> # Output I'm an assoc array. I'm an assoc array. "Associative arrays are arrays that use named keys that you assign to them." https://www.w3schools.com/php/php_arrays.asp Solution: <?php function is_assoc(array $array) { return count(array_filter(array_keys($array), 'is_string')) > 0; } function test(array $array) { echo is_assoc($array) ? "I'm an assoc array.\n" : "I'm not an assoc array.\n"; } // an assoc array $a = array("a"=>"aaa","b"=>1,"c"=>true); test($a); // an array $b = array(0=>"aaa",1=>1,3=>true); test($b); ?> # Output I'm an assoc array. I'm not an assoc array. If you want check pure assoc. array replace > 0 by === count($array) ---- Server IP: 208.43.231.9 Probable Submitter: 185.85.3.195 (proxied: 37.14.57.118) ---- Manual Page -- http://php.net/manual/en/function.is-array.php Edit -- https://master.php.net/note/edit/124039 Del: integrated -- https://master.php.net/note/delete/124039/integrated Del: useless -- https://master.php.net/note/delete/124039/useless Del: bad code -- https://master.php.net/note/delete/124039/bad+code Del: spam -- https://master.php.net/note/delete/124039/spam Del: non-english -- https://master.php.net/note/delete/124039/non-english Del: in docs -- https://master.php.net/note/delete/124039/in+docs Del: other reasons-- https://master.php.net/note/delete/124039 Reject -- https://master.php.net/note/reject/124039 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#211603) next »