Home  >  Article  >  Backend Development  >  How to determine whether it is an indexed array in php

How to determine whether it is an indexed array in php

WBOY
WBOYOriginal
2016-07-25 09:12:241881browse

Example, detect whether a php array is an index array.

  1. function is_assoc($arr){
  2. return array_keys($arr) !== range(0, count($arr) - 1);
  3. // array_values($arr) ! == $arr
  4. }
  5. function is_assoc2($array) {
  6. return (bool)count(array_filter(array_keys($array), 'is_string'));
  7. }
  8. $array = array(0=>"1" ,1=>"3");
  9. var_dump($array);
  10. echo is_assoc($array)?'Index array':'Not an index array';
  11. echo "
    ";
  12. echo is_assoc2 ($array)?'Indexed array':'Not an indexed array';
  13. echo "
    ";
  14. $array = array("0"=>"1","1"=> "3");
  15. var_dump($array);
  16. echo is_assoc($array)?'index array':'not an index array';
  17. echo "
    ";
  18. echo is_assoc2($array)? 'Index array': 'Not an index array';
  19. echo "
    ";
  20. $array = array("name"=>"1","age"=>"3");
  21. var_dump($array);
  22. echo is_assoc($array)?'index array':'not an index array';
  23. echo "
    ";
  24. 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


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn