Example, detect whether a php array is an index array.
-
- function is_assoc($arr){
- return array_keys($arr) !== range(0, count($arr) - 1);
- // array_values($arr) ! == $arr
- }
- function is_assoc2($array) {
- return (bool)count(array_filter(array_keys($array), 'is_string'));
- }
- $array = array(0=>"1" ,1=>"3");
- var_dump($array);
- echo is_assoc($array)?'Index array':'Not an index array';
- echo "
";
- echo is_assoc2 ($array)?'Indexed array':'Not an indexed array';
- echo "
";
-
- $array = array("0"=>"1","1"=> "3");
- var_dump($array);
- echo is_assoc($array)?'index array':'not an index array';
- echo "
";
- echo is_assoc2($array)? 'Index array': 'Not an index array';
- echo "
";
-
- $array = array("name"=>"1","age"=>"3");
- var_dump($array);
- echo is_assoc($array)?'index array':'not an index array';
- echo "
";
- echo is_assoc2($array)?'index array': 'Not an indexed array';
Copy code
output:
array (size=2)
0 => string '1' (length=1)
1 => string '3' (length=1)
Not an indexed array
Not an indexed array
array (size=2)
0 => string '1' (length=1)
1 => string '3' (length=1)
Not an indexed array
Not an indexed array
array (size=2)
'name' => string '1' (length=1)
'age' => string '3' (length=1)
index array
Index array |