Fedir RYKHTIK
Fedir RYKHTIK

Reputation: 9994

PHP associative array's keys (indexes) limitations?

If there are some kind of limitations for array keys in PHP ? Length ? Not acceptable strings ?

In the official documentation found only this, but there is no information about keys limitations.

A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08"). Floats in key are truncated to integer. The indexed and associative array types are the same type in PHP, which can both contain integer and string indices.*

Upvotes: 12

Views: 15605

Answers (3)

tycho martins
tycho martins

Reputation: 7

are you sure you're refering to the key? or do you mean value?

with associative arrays : $array = new array( new array( "key"=>"value" ) );

.. as for the key i think in theorie there's no limitations to length however .. chosing long keys isn't a good idea if you'll want to reusre them a lot..

as for the values you should just take a loot at arrays in general and what datatypes are allowed and stuff..

hope this helps..

Upvotes: -2

rodneyrehm
rodneyrehm

Reputation: 13557

Any string used as a key in an array is hashed. Analogous to md5() and sha1() this hashing reduces (potentially gigabytes of) characters to a known length. unlike md5() or sha1() the array's internal hashing mechanism will convert your string to an integer it can then use to address a bucket within the array. PHP's arrays aren't true/real arrays - they are some sort of Linked HashMap internally. Considering that multiple strings can boild down to the same hash, each bucket is a list itself. If there are multiple elements within the same bucket, each key has to be evaluated. It goes without saying that short keys are compared faster than 1MB of text.

TL;DR: although you are not limited by PHP, you should limit yourself. If you have fairly long strings, consider running them through md5() or sha1() (or any other hashing function, actually) to reduce the key length.

Upvotes: 11

MichaelH
MichaelH

Reputation: 1620

What is the max key size for an array in PHP?

This question is almost the exact same. But if you dont want to trust anything unofficial, just stick to using less small keys. You may even get some performance benefits out of it.

EDIT: And as the The PHP Manual says:

Note: It is no problem for a string to become very large. PHP imposes no boundary on the size of a string; the only limit is the available memory of the computer on which PHP is running..

Upvotes: 8

Related Questions