Home  >  Article  >  Backend Development  >  PHP accurately determines whether it is an index array

PHP accurately determines whether it is an index array

巴扎黑
巴扎黑Original
2016-11-21 13:34:571325browse

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)?'索引数组':'不是索引数组';
echo "
"; echo is_assoc2($array)?'索引数组':'不是索引数组'; echo "
"; $array = array("0"=>"1","1"=>"3"); var_dump($array); echo is_assoc($array)?'索引数组':'不是索引数组'; echo "
"; echo is_assoc2($array)?'索引数组':'不是索引数组'; echo "
"; $array = array("name"=>"1","age"=>"3"); var_dump($array); echo is_assoc($array)?'索引数组':'不是索引数组'; echo "
"; echo is_assoc2($array)?'索引数组':'不是索引数组';
array (size=2)
  0 => string '1' (length=1)
  1 => string '3' (length=1)
不是索引数组
不是索引数组
array (size=2)
  0 => string '1' (length=1)
  1 => string '3' (length=1)
不是索引数组
不是索引数组
array (size=2)
  'name' => string '1' (length=1)
  'age' => string '3' (length=1)
索引数组
索引数组



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