Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays with NULL keys

Tags:

arrays

php

null

PHP trivia here.

If we declare an array like this:

<?php $arr = [ 'foo' => 'bar', NULL => 'hello' ]; ?> 

We can access it like this

print $arr[NULL]; 

This will print hello. Why is this useful, relevant or necessary? Is it a PHP bug or a feature?

My only idea was that you could declare array with the NULL key being equal to an error message to explain to anyone who uses a NULL key that their key is null:

$arr[NULL] = 'Warning you have used a null key, did you mean to?'; 

Has anyone found this useful? Seems to be something to cause more harm than good.

like image 396
ddoor Avatar asked Aug 15 '13 06:08

ddoor


People also ask

Can arrays have null values?

An array value can be non-empty, empty (cardinality zero), or null. The individual elements in the array can be null or not null.

How do you declare a null value in an array?

int[] a = new int[5]; a[0] = 1; a[2] = 'a'; a[3] = null; //Compiler complains here for (int i : a) System. out. println(i);

Can an array have keys?

No. Arrays can only have integers and strings as keys.

What is array_keys () used for?

The array_keys() function returns all the keys of an array. It returns an array of all the keys in array.


2 Answers

Quote from the manual:

Null will be cast to the empty string, i.e. the key null will actually be stored under "".

Additional details about how keys are cast are as follows:

The key can either be an integer or a string. The value can be of any type.

Additionally the following key casts will occur:

  • Strings containing valid decimal integers, unless the number is preceded by a + sign, will be cast to the integer type. E.g. the key "8" will actually be stored under 8. On the other hand "08" will not be cast, as it isn't a valid decimal integer.
  • Floats are also cast to integers, which means that the fractional part will be truncated. E.g. the key 8.7 will actually be stored under 8.
  • Bools are cast to integers, too, i.e. the key true will actually be stored under 1 and the key false under 0.
  • Null will be cast to the empty string, i.e. the key null will actually be stored under "".
  • Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.

As for this being useful or necessary, this is debatable. You are asked to use integer or string keys and you have been warned about implicit key casting.

like image 122
Salman A Avatar answered Sep 20 '22 01:09

Salman A


I have found the possibility to have Null keys useful, when accessing db, using a class, which can use one of the column values as the key to the returned array. Some column values could be null.

like image 25
mikewasmike Avatar answered Sep 20 '22 01:09

mikewasmike