93

I have some php array keys that are populated with a lot of weird characters.

Is this allowed? Are there any constraints to what I cannot use?

Damien Pirsy
  • 25,319
  • 8
  • 70
  • 77
cgwebprojects
  • 3,382
  • 6
  • 27
  • 40

12 Answers12

98

According to the 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.

The manual again:

A string is series of characters, where a character is the same as a byte. This means that PHP only supports a 256-character set, and hence does not offer native Unicode support. See details of the string type.

So in short, any string can be a key. And a string can contain any binary data (up to 2GB). Therefore, a key can be any binary data (since a string can be any binary data).

Some random (valid) abuse of array keys:

$w = array(chr(0) => 'null byte?', chr(rand(0, 255)) => 'random byte?');
var_dump($w);
Corbin
  • 33,060
  • 6
  • 68
  • 78
  • 1
    To clarify, that does not mean you can't use Unicode strings as array keys. In fact, *any* binary string works just fine. I find PHP's self-described lack of Unicode support annoying, since it's not really true. :) – deceze May 22 '12 at 05:25
  • 1
    @deceze Unicode falls under the category of "any binary data" :) (though I guess with the manual's wording, I suppose that clarification is necessary). And saying "does not offer native Unicode support" is true enough. There's PHP core doesn't include Unicode versions of strlen, substr, etc. Though "does not offer native processing of Unicode strings" might be more appropriate. – Corbin May 22 '12 at 05:28
  • 3
    Sure, the core does not contain any facilities to *manipulate* Unicode strings. But as long as you don't want to manipulate strings, PHP supports them just fine. And realistically speaking, the MB extension is available on virtually every PHP installation by default, so the distinction between "core support" or not is mostly academic. :) – deceze May 22 '12 at 05:32
  • 1
    @deceze maybe their note should read "not natively (see mb extension)" or something then. You're right though. Any PHP installation since 2005 essentially supports Unicode, though I would argue that the support of Unicode in PHP (with extensions) is still a bit unpleasant. – Corbin May 22 '12 at 05:33
  • @Corbin, why do you call that *abuse* instead of *use*? – Pacerier Aug 07 '13 at 14:24
12

The key must be a string or an integer. There are some casts that take place, but I think the manual does a good job of explaining:

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.
Matthew
  • 47,584
  • 11
  • 86
  • 98
  • Resource types can be cast to integer now (not sure if this is a new feature), so you can use eg a file handle or curl handle as a key indirectly by casting it to integer and using that as the key. – thomasrutter May 16 '19 at 05:54
11

My answer is very outdated now - It was probably an older version of PHP or some measurement error.


I found this answer looking for more information on a problem I had. I was using strings with UTF-8 characters in them, which would not work as keys to an array I had.

Something like

$str = "R&D - Solution";
$arr = array( "R&D - Solution" => "Research" );
echo $arr[$str];  // did not work

The (not big or clever) solution for me was to do this..

$str = md5("R&D - Solution");
$arr = array( md5("R&D - Solution") => "Research" );
echo $arr[$str];  // works!
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Rob
  • 453
  • 1
  • 7
  • 14
  • 2
    I like md5() for generating array keys. Even if it's not entirely necessary at this point it still feels safer. – But those new buttons though.. Oct 31 '14 at 19:31
  • 7
    Were you using an older version of PHP? Your first example works fine in PHP 7.1. – Elliot B. Feb 22 '19 at 21:56
  • `bin2hex` is better to use as a key because it is guaranteed to be unique, unlike `md5` and will always revert back to the original by using `hex2bin`. Probably much faster than `md5` as well. – Patanjali Nov 23 '20 at 07:43
  • 3
    My answer is very outdated now - It was an older version of PHP. Plus bin2hex might be more performant. Although md5 is incredibly likely to be unique, neither is needed in this situation with the bug not present on recent PHP versions. – Rob Mar 04 '21 at 12:38
7

PHP array keys can be integers or strings. PHP strings are byte arrays, meaning sequences of bytes. There are no other types of strings and PHP doesn't otherwise impose any special restrictions on array key strings. In other words: as long as it's a string, anything goes.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • 1
    I think the implicit cast from a string to an integer key is an important distinction to make, since certain functions operate differently if the key is an integer or not. e.g., You may use arbitrary string numbers only to find that an array function later reindexes them from 0..n-1. – Matthew May 22 '12 at 05:27
  • 1
    Agreed, but I'd think it's on the borderline of the scope of this question. :) – deceze May 22 '12 at 05:33
5

Anything you can stuff into a PHP string can be used as an array key. There's no limit on the characters allowed.

$a = array();

$x = 'long string of random garage';
echo $a[$x]; // this is ok

$x = array();
echo $a[$x]; // not ok
Marc B
  • 356,200
  • 43
  • 426
  • 500
1

If complex keys are causing an "undefined index" error, you may simply have a "trim" problem.

I was going nuts because a complex key was spitting out the "undefined index" error and I thought maybe it was a syntax violation. The array key causing the error was built from a field from a MySQL database query that I was converting into a key and using in a new array. The key looked like this: pl_1DNKoiJKwotCqAycickBVhTy and here's how the code was constructed.

//new array created from database query
$new_array[$dbquery['fieldname']] = {some value};

//key value found in field of second array
$keyval = $array_two['fieldname'];

//this produced the "undefined index" error
echo $new_array[$keyval];

when, in fact, the $keyval and $dbquery['fieldname'] appeared to be a perfect match (visually verified by echoing both to the browser). The mystery was solved by simply using trim in the second statement like this: $keyval = trim($array_two['fieldname']); Once 'trimmed', php no longer complained.

Hoping this saves some others from some frustrating moments...

globalSchmidt
  • 1,329
  • 16
  • 28
0

I've personally not had any problems with unusual characters in array keys. What is and isn't legal isn't well documented, other than to say that the key must be a scalar. Your best bet is to just try it and see.

GordonM
  • 31,179
  • 15
  • 87
  • 129
0

In addition to all the answers as they are true: You can use PSRs that they are some kind of rules between best programmers for having a nice and standard coding style.

VeRJiL
  • 415
  • 4
  • 13
0

In php array you cannot use key : 2.3 or decimal numbers

abhishek92
  • 61
  • 4
0

For this peace of code :

$a = (object) ['@km³' => 123];

This :

error_log($a->@km³);

Produce this error :

PHP Parse error: Syntax error, unexpected '@', expecting T_STRING or T_VARIABLE or '{' or '$' on line 1

But this is working :

error_log($a->{"@km³"});

(with {})

Elikill58
  • 4,050
  • 24
  • 23
  • 45
-1

Encode the php page in ANSI "é" will be able for use (Cinéma wont show up as Cinéma). In Notepad++ just use the menu Encode=>Convert ANSI and save

Fab
  • 1
  • 2
    (This post does not seem to provide a [quality answer](https://stackoverflow.com/help/how-to-answer) to the question. Please either edit your answer, or just post it as a comment to the question). – sɐunıɔןɐqɐp Sep 10 '18 at 12:24
  • Can you explain that further? What if `é` is not present, what if the OP does not use Notepad++ after all? – Nico Haase Feb 01 '19 at 10:36
-1
$sKey="C:\music\R&B - Stas mihailov.mp3";
$sKey=str_replace("&","_amp_",$sKey);//encode
$mArray[$sKey]="album name Сheeks Dance";
foreach($mArray as$sKey=>$v){
 $sKey=str_replace("_amp_","&",$sKey);//decode
 ..
    
 }
Uxoos
  • 11
  • 2
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 12 '23 at 07:55