How to check if the key is set or not in PHP

Viewed 92

How to check if the key of array is set or not in PHP

How do I tell the difference between the two?

$a = [
          'a' => ['key' => 'value'],
          ['key' => 'value']
        ];
$a = [
          'a' => ['key' => 'value'],
          '0' => ['key' => 'value']
        ];

The difference is that the first one does not have an index number but the default is 0 (['key' => 'value']) but second has 0 index ('0' => ['key' => 'value'])

Note: It does not make sense to check whether the key is an array of numbers or not because the user may give the number.

2 Answers

Your question has no answer, because the two arrays are not different: they are just different ways of writing the same thing.

To understand what I mean by that, consider this question:

How can I tell the difference between the integer 1 + 3 and the integer 2 + 2?

When you look at the source code of $a = 1 + 3; and $a = 2 + 2; you can see the difference; but when PHP executes that code, it will assign the value 4 in both cases. You can't write code that examines $a and works out why it is 4, or how it was calculated.

The same is true of the two array literals you show. Although they look different in your source code, once executed, PHP will assign the same array value in both cases.

The "canonical" version actually looks like this:

$a = [
   'a' => ['key' => 'value'],
   0 => ['key' => 'value']
];

The string '0' is considered the same key as the integer 0, and entries without indexes written are assigned integer indexes in order, starting at 0.

With array_key_exists() you can check whether a key exists.

$a = [
          'a' => ['key' => 'value'],
          ['key' => 'value']
        ];

var_dump(array_key_exists('0',$a));
//bool(true)

var_dump(array_key_exists(0,$a));
//bool(true)

The key 0 exists because the above code is only a short form of

$a2 = [
          'a' => ['key' => 'value'],
          '0' => ['key' => 'value']
        ];

If the key is a number, it is always stored as an integer.

foreach($a2 as $key => $val){
  var_dump($key);
}   
// string(1) "a" 
// int(0)

Arrays can also be compared directly. The strict comparison also shows that $a and $a2 are identical.

var_dump($a === $a2); //bool(true)
Related