0

I am trying to do the below in php

array(
  'email@domain.com' => 'something',
  ...
);

I did read that php accepts and number or valid string as key.

is it safe to have email id as key in the array as above ? by safe I mean is possible that this could cause any kind of error or exception or problem when coding wit this

Note: I would be having several 100 items in this array is there something that I need to take care while I do this

Please let me know

1 Answers1

5

Short answer: If it can be a string in PHP, nowadays, it can safely be used as an associate array key.

Long answer: From the PHP manual:

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 integers 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.

If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.

Community
  • 1
  • 1
David Wyly
  • 1,671
  • 1
  • 11
  • 19
  • this almost looks safe, but consider if any string LEADING with number, will be converted to an int, and will trunkate the rest "8mile@bigfen.com" will be stored as `8`. So if you have any control over the email and you are SURE they are in a format "firstname.lastname..." it can work, but not for public emails. – d.raev Jun 15 '20 at 09:48
  • 1
    @d.raev I just did a local test and the same email example you used (`8mile@bigfen.com`) with a leading number did not truncate down to `8`. Which seems in alignment with the the PHP manual casting rules that I linked. I'm not sure how you've come to your conclusion, can you care to elaborate? – David Wyly Sep 17 '20 at 09:52