【问题标题】:How can I check that an array key exist if the array does not exist in PHP如果 PHP 中不存在数组,如何检查数组键是否存在
【发布时间】:2010-11-25 10:05:50
【问题描述】:

我在一个页面上多次绑定不同的表单项,我只在存在 error_array 键的情况下将 css div 类插入表单项,这就是我突出显示其中有错误的表单项的方式.

工作,如果我有一个错误很好,因为我的错误数组被设置,问题是在设置错误之前,它试图寻找一个不存在的数组键。我在想首先使用 php 的 isset 函数将是票,但我想你不能将 isset 与另一个函数结合起来?


<?php
//this works
$search_array = array('first' => 1, 'second' => 4);

if (array_key_exists('first', $search_array)){
    echo "good";
}


// this does not work, will give write errors
$search_array = array('first' => 1, 'second' => 4);

if (isset(array_key_exists('first', $search_array))){
    echo "good";
}

// Here is  1 example how I need to make the end result work
$country_class = (array_key_exists('country', $signup_errors)) ? ' signup_error' : ' signup_good';
echo '<select name="country" id="country" class="textarealong ' .$country_class. '"/>';
?>

其他部分我是这样用的

<?PHP echo(array_key_exists('password', $signup_errors)) ? ' signup_error' : ' signup_good';?>

如果可能的话,我需要将其设为 1 行代码

【问题讨论】:

    标签: php arrays


    【解决方案1】:

    如果 isset 为假,则不会执行第二条语句,因为解析器知道两个语句都必须为真才能使整个语句为真。

       $country_class = ( isset($signup_errors) && array_key_exists('country', $signup_errors)) ? ' signup_error' : ' signup_good';
    

    但我建议您初始化您正在使用的 每个 变量...

    【讨论】:

    • 还有关于你的评论,这不是初始化这个变量吗?
    • 不,它不会因为即使array_key_exists 自动激活$signup_errors(我很确定它不会),那么isset() 的失败将导致它根本无法运行. isset() 显然不允许激活它测试的变量。
    【解决方案2】:

    我对 PHP 语法不够熟悉,但这听起来像是短路评估的工作,即 ||或 &&,如果仅第一项可以确定结果(如果 || 为 True 或 && 为 False),则不计算第二项。

    【讨论】:

      【解决方案3】:

      这是一个老问题,但它是一个更简单的答案。 isset 检查数组和密钥。这很好用,如果未设置数组,则不会生成任何通知:

      if (isset($search_array['first'])){
          echo "good";
      }
      

      或者:

      $country_class = isset($signup_errors['country']) ? ' signup_error' : ' signup_good';
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-26
        • 2016-08-07
        • 2012-10-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多