1

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) 
Pontiac_CZ
  • 619
  • 1
  • 6
  • 13

2 Answers2

3

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

Robert
  • 19,800
  • 5
  • 55
  • 85
  • And what about two dimensional array? – Pontiac_CZ Aug 02 '16 at 07:41
  • it's the same but you need to check first dimension then second one etc. check http://stackoverflow.com/questions/19420715/check-if-specific-array-key-exists-in-multidimensional-array-php – Robert Aug 02 '16 at 09:45
0

In php7+ you can use null coalescing:

if(self::ARR['a']??false){

}
4b0
  • 21,981
  • 30
  • 95
  • 142
grafhax
  • 11
  • 1