duanhuo0577 2016-08-01 13:13
浏览 74

如何判断PHP常量数组键是否存在?

I want to use an array as a constant in PHP 5.6. The question is: how to check whether a key 'a' exists in the array and get the "Test2" return true as well?

My code now is like this:

const ARR = array(
   'a' => 'first',
   'b' => 'second'
);


$test1 = defined("ARR");
$test2 = defined("ARR['a']");

echo '<br>Test1: ';
var_dump($test1);

echo '<br>Test2: ';
var_dump($test2);

Result:

Test1: bool(true)
Test2: bool(false) 
  • 写回答

1条回答 默认 最新

  • dsbqfrr098575666 2016-08-01 13:15
    关注

    You need to use array_key_exists function

    var_dump(array_key_exists('a', ARR));
    

    defined() checks if constant is defined and it is, so you can additionaly check if constant is array with is_array(ARR);

    Example:

    <?php
    
    const ARR = array(
       'a' => 'first',
       'b' => 'second'
    );
    
    
    $test1 = array_key_exists('a', ARR);
    $test2 = array_key_exists('c', ARR);
    
    echo 'Test1: ';
    var_dump($test1);
    
    echo 'Test2: ';
    var_dump($test2);
    

    Output:

    Test1: bool(true)
    Test2: bool(false)
    

    Notice:

    It will work only with PHP version >= 5.6 Working fiddle

    评论

报告相同问题?

悬赏问题

  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题