【问题标题】:array_key_exists is not working wellarray_key_exists 运行不正常
【发布时间】:2016-04-20 18:11:59
【问题描述】:

我有这个数组:

$variableNames = [
        'x1',
        'x2',
        'x3',
        'x4',
        'x5',
        'x6',
        'x7'
    ];

但是,当我像这样使用 array_key_exists 函数时:

array_key_exists('x3', $this->variableNames)

它返回false。但是,如果我有这个数组:

$variableNames = [
        'x1' => null,
        'x2' => null,
        'x3' => null,
        'x4' => null,
        'x5' => null,
        'x6' => null,
        'x7' => null
    ];

它返回true。我如何使用第一个数组并获得true? 在第一个数组中,值也为空,就像第二个数组一样。那么,为什么第一个数组返回false,第二个数组返回true

【问题讨论】:

  • 在上面的数组中使用 in_array() 导致键是 0,1,2... 不是 'x1'.....
  • 我相信代码在你的第一种情况下认为“键”是值并使键为 0、1、2 等。尝试 var_dump 第一个情况
  • 您将键与值混淆了,在您的数组中,键是隐含的 0=>x1 等等

标签: php arrays array-key-exists


【解决方案1】:

array_key_exists() 搜索键而不是值。

在您的第一种情况下,您 x3 是有价值的。

所以,它没有搜索。

在这种情况下你可以使用in_array(),这个函数搜索 价值。

在第二种情况下,x3 是关键,因此可以正确搜索。

【讨论】:

    【解决方案2】:

    键不为空,永远不会。

    $variableNames = [
            'x1',
            'x2',
            'x3',
            'x4',
            'x5',
            'x6',
            'x7'
        ];
    

    表示

    $variableNames = [
            0 => 'x1',
            1 => 'x2',
            2 => 'x3',
            3 => 'x4',
            4 => 'x5',
            5 => 'x6',
            6 => 'x7'
        ];
    

    使用

    in_array('x3', $this->variableNames)
    

    改为。

    【讨论】:

      【解决方案3】:

      使用in_array() 而不是array_key_exists()

      在你的情况下,

      $variableNames = ['x1',
              'x2',
              'x3',
              'x4',
              'x5',
              'x6',
              'x7'];
      
      if (in_array("x3", $this->variableNames)) {
          echo "Found x3";
      }
      

      【讨论】:

        【解决方案4】:

        不,你不正确。该功能运行良好,您只是使用不正确。 array_key_exists 寻找的是键,而不是值。

        您提供的第一个数组实际上被视为一个值数组。它们有索引键,由 PHP 自动添加。我你print_r($variableNames),你会看到它会返回以下内容。

        $variableNames = [
                0 => 'x1',
                1 => 'x2',
                2 => 'x3',
                3 => 'x4',
                4 => 'x5',
                5 => 'x6',
                6 => 'x7'
            ];
        

        您需要改为搜索该值。使用in_array()isset(),两种方式都对,一种比另一种方便。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-08-16
          • 2010-09-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-12-18
          • 2021-10-24
          • 2014-10-04
          相关资源
          最近更新 更多