Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP associative array's keys (indexes) limitations?

Tags:

arrays

php

key

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

like image 711
Fedir RYKHTIK Avatar asked Feb 29 '12 09:02

Fedir RYKHTIK


People also ask

Are PHP array keys case sensitive?

Yep, array keys are case sensitive.

Which array can store multiple index values in PHP?

In the previous pages, we have described arrays that are a single list of key/value pairs. However, sometimes you want to store values with more than one key. For this, we have multidimensional arrays.

What are the advantages of associative arrays in PHP?

Advantages of Associative ArrayWe can save more data, as we can have a string as key to the array element, where we can have associated data to the value to be stored, like in our example, we stored the type of the car as key along with the name of the car as value.


2 Answers

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.

like image 102
rodneyrehm Avatar answered Nov 07 '22 08:11

rodneyrehm


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

like image 8
MichaelH Avatar answered Nov 07 '22 10:11

MichaelH