【问题标题】:How can I do this with PHP arrays?如何使用 PHP 数组做到这一点?
【发布时间】:2009-09-03 04:24:35
【问题描述】:
<?PHP
$signup_errors = array();
$signup_errors['captcha'] = 'test 1';
$signup_errors['something'] = 'test 2';
$signup_errors['another'] = 'test 3';
$signup_errors['getthepoint'] = 'test 4';

//this would work
if (isset($signup_errors) && in_array('test 4', $signup_errors)){
    echo 'it works';
} 

//However I need something like this to work
if (isset($signup_errors) && in_array('captcha', $signup_errors)){
    echo 'it works';
} 
?>

这里的最终目标是有一个 html 表单,我可以在其中更改 css div 类名是否存在错误数组项,所以如果它返回这个

$signup_errors['captcha'] = 'Please enter the correct security code';

然后在提交的表单上我会有这样的东西

<input type="text" class="textarealong <?PHP if (isset($signup_errors) && in_array('captcha', $signup_errors)){echo 'error-class';}?> " value=''>

【问题讨论】:

    标签: php arrays


    【解决方案1】:

    array_key_exists代替in_array

    <input type="text" class="textarealong <?PHP if (isset($signup_errors) && array_key_exists('captcha', $signup_errors)){echo 'error-class';}?> " value=''>
    

    【讨论】:

      【解决方案2】:

      好的,我想我明白了,php 密钥存在似乎可以解决问题

      <?php
      $search_array = array('first' => 1, 'second' => 4);
      if (array_key_exists('first', $search_array)) {
          echo "The 'first' element is in the array";
      }
      ?>
      

      【讨论】:

        【解决方案3】:

        在你的情况下,我会使用

        isset($search_array['first']);
        

        而不是

        array_key_exists('first', $search_array);
        

        这对我来说可能更快、更易读。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-09-19
          • 2019-04-30
          • 2017-09-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多