【问题标题】:Check if an array it not a indexed array [duplicate]检查数组是否不是索引数组[重复]
【发布时间】:2023-04-02 04:31:01
【问题描述】:

我需要检查一个特定的数组是 keyed 还是索引。例如:

// Key defined array
array('data-test' => true, 'data-object' => false);

// Indexed array
array('hello', 'world');

我可以轻松地使用数组键执行foreach 来检查是否全部为整数。但是存在一个正确的方法来检查它吗?内置 PHP 函数?

可能的解决方案

// function is_array_index($array_test);
//    $array_test = array('data-test' => true, 'data-object' => false);

foreach(array_keys($array_test) as $array_key) {
    if(!is_numeric($array_key)) {
        return false;
    }
}

return true;

【问题讨论】:

    标签: php arrays


    【解决方案1】:
    function is_indexed($arr) {
      return (bool) count( array_filter( array_keys($arr), 'is_string') );
    }
    

    【讨论】:

      【解决方案2】:

      这是来自php.net function.is-array

      function is_assoc($array) {
          return (is_array($array) && 0 !== count(array_diff_key($array, array_keys(array_keys($array)))));
      }
      

      【讨论】:

        【解决方案3】:

        您可以检查密钥[0]

        $arr_str = array('data-test' => true, 'data-object' => false);
        
        $arr_idx = array('hello', 'world');
        
        if(isset($arr_str[0])){ echo 'index'; } else { echo 'string'; }
        
        echo "\n";
        
        if(isset($arr_idx[0])){ echo 'index'; } else { echo 'string'; }
        

        示例:http://codepad.org/bxCum7fU

        【讨论】:

          【解决方案4】:

          功能

          function isAssoc($arr)
          {
              return array_keys($arr) !== range(0, count($arr) - 1);
          }
          

          应该可以。

          【讨论】:

            猜你喜欢
            • 2010-09-20
            • 2018-07-19
            • 1970-01-01
            • 2021-07-30
            • 2012-01-09
            • 2012-11-05
            • 1970-01-01
            相关资源
            最近更新 更多