dongyu1125 2014-04-27 09:56
浏览 92
已采纳

php - 为什么关联数组的第一个元素的键不能为零?

I am new to associative array concept of php. I had never used associative array before this. I came through an example, and got the following code:

function isAssoc($arr)
{
    return array_keys($arr) !== range(0, count($arr) - 1);
}
echo(var_dump(isAssoc(array("0" => 'a', "1" => 'b', "2" => 'c'))).'<br />'); // false
echo(var_dump(isAssoc(array("1" => 'a', "1" => 'b', "2" => 'c'))).'<br />'); //true
echo(var_dump(isAssoc(array("1" => 'a', "0" => 'b', "2" => 'c'))).'<br />'); // true
echo(var_dump(isAssoc(array("a" => 'a', "b" => 'b', "c" => 'c'))).'<br />'); // true

The above function is used to tell whether the array is associate array or not.

I have this doubt why:

array("0" => 'a', "1" => 'b', "2" => 'c')

is not an associative array as it returns false. Whereas,

array("1" => 'a', "0" => 'b', "2" => 'c') //OR
array("1" => 'a', "1" => 'b', "2" => 'c')

is an associative array?

  • 写回答

3条回答 默认 最新

  • dpmopn8542 2014-04-27 10:26
    关注

    The function you're referring to has flaws and it is not authoritative about the fact whether or not an array in PHP is associative or not.

    In-fact, in PHP it is not strictly defined what the term associative array actually means.

    However it is important to understand that

    1. PHP is loosely typed
    2. PHP differs in array keys between integer (bool, NULL, float, integer, numeric string represented as integer) and string (nun-numeric strings) for keys.

    Most likely an associative array in PHP is one where inside the array (that is after creating it, not while it seems when writing the array definition) that all keys in that array are strings.

    But keep in mind that no set-in-stone definition exists. PHP arrays are just a mixture of array and hash-map where you need to know both without having both properly differentiated and the need to keep in mind the difference between numeric and non-numeric keys and how the loosely type-system of PHP converts for the array key needs.

    First page to go as usual:


    For those who really can only understand it with code, here the pony goes:

    function is_array_assoc(array $array) {
        return is_array($array);
    }
    

    If you can ensure that you're not using an error-handler that catches catchable errors, then the following code is correct, too:

    function is_array_assoc(array $array) {
        return TRUE;
    }
    

    The later example makes it perhaps a bit more clear that all arrays in PHP are associative.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?