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) 
1
  • 1
    $test2 = isset(ARR['a']); (PHP7) Commented Aug 1, 2016 at 13:14

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

And what about two dimensional array?
it's the same but you need to check first dimension then second one etc. check stackoverflow.com/questions/19420715/…
0

In php7+ you can use null coalescing:

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

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.