在 PHP 中,数组键是什么?

4

我正在尝试理解这段代码:

<?php 

$list = array(-10=>1, 2, 3, "first_name"=>"mike", 4, 5, 10=>-2.3); 

print_r(array_keys($list));
?> 

输出:

Array ( [0] => -10 [1] => 0 [2] => 1 [3] => first_name [4] => 2 [5] => 3 [6] => 10 ) 

我想知道为什么[4] => 2[5] => 3,我原以为应该是[4] => 4[5] => 5,因为它们都在索引4和5处。我对这个数组中正在发生的事情有点困惑,如果可能的话,有人能指导一下我吗?谢谢。

5个回答

6

您将键入的数组条目与无键的数组条目混合使用,因此会变得有点混乱:

$list = array(
    -10 => 1   // key is -10
        => 2  // no key given, use first available key: 0
        => 3  // no key given, use next available key: 1
    "first_name" => "mike" // key provided, "first_name"
        => 4  // no key given, use next available: 2
        => 5  // again no key, next available: 3
     10 => -2.3  // key provided: use 10

如果您不提供一个键,PHP会分配一个从0开始的键。如果潜在的新键与已经分配的键冲突,那么这个潜在的键将被跳过,直到PHP找到可以使用的键为止。

谢谢您的解释,不幸的是这段代码是由我的大学过去试卷的考官编写的,所以如果它使用了错误的技术,那就相当糟糕。 - user3562135
这并不是真正的“错误”。但如果你不知道发生了什么,它会让人感到困惑。我的一般规则是永远不要做这种事情,因为它可能导致混乱。 - Marc B

1

这是正常的,因为PHP正在等待一个键。

$list = array(-10=>1, 2, 3, "first_name"=>"mike", 4, 5, 10=>-2.3); 

如果你没有给他2、3、4、5,那么它会自动给出一个键。

所以 ==> [0] => 2,[1] => 3,[2] => 4和[3] => 5。


1

try this:

$list = array(-10=>1, 2 => null, 3=> null, "first_name"=>"mike", 4=> null, 5=> null, 10=>-2.3);

为了得到您想要的结果,因此2、3、4和5将被视为键而不是值。

0

看起来当键未设置时,array_keys 会跟踪上一个分配的键,并将连续的数字分配给它:

array(7) {
  [0]=>
  int(-10)
  [1]=>
  int(0)   // first without key (starting on 0)
  [2]=>
  int(1)   // second without key
  [3]=>
  string(10) "first_name"
  [4]=>
  int(2)  // third without key 
  [5]=>
  int(3)  // fourth without key
  [6]=>
  int(10)
}

0
在你的数组中,你混合使用了 key => value 和只有 value 的写法。
-10 是你的第一个键。然后因为你没有为接下来的项目定义键,它会按顺序自动分配键值。

数组可以具有负数键。 - hindmost

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接