A numeric string as array key in PHP

A numeric string as array key in PHP

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Preserving String Keys in PHP Arrays

By default, PHP employs a process known as juggling when you define an array key using a numeric string. If you assign a value to $blah['123'], the engine immediately attempts to cast that string into an integer. This conversion happens automatically because 123 is a valid integer literal. The resulting data structure displays with [123] as the key, and attempting to access it via $blah['123'] or $blah[123] yields identical results.

This behavior stems from PHP's internal array implementation, which optimizes for numeric indices by storing them as integers rather than strings. While this optimization improves memory usage and lookup speeds for standard lists, it creates friction when your application logic requires distinguishing between a string key "123" and an integer key 123.

To force PHP to treat the key strictly as a string, you must explicitly tell the engine not to perform the cast. The most direct method is using curly braces around the key in your array definition:

$blah = ['{123}' => 1];
var_dump($blah);

This outputs:

array(1) {
  ["123"]=>
  int(1)
}

The curly braces act as a delimiter that prevents the numeric string from being interpreted as a number. This syntax is critical when your keys contain leading zeros or are otherwise ambiguous in standard notation. For instance, if you need a key like '01', PHP would normally cast this to integer 1. By using {01}, you ensure it remains the string '01'.

Handling Complex Keys and JSON Compatibility

The distinction between numeric strings and integers becomes particularly relevant when interacting with external data formats like JSON. When you serialize a PHP array containing mixed key types, the internal structure is preserved:

$data = ['{0}' => 'zero', '1' => 'one'];
$json = json_encode($data);
echo $json; 
// Output: {"0":"zero","1":"one"} (Note: JSON does not distinguish key types)

However, the internal representation matters when deserializing data or using specific libraries. If you retrieve data from an API where keys are guaranteed to be strings, relying on implicit casting can lead to subtle bugs. For example, a validation rule might expect the string '123' but inadvertently match against the integer 123 if your array juggling merges them into a single bucket.

Trade-offs and Performance Considerations

While using {...} syntax guarantees the key remains a string, it introduces a slight overhead. PHP's internal hash table is optimized for integer keys; string keys require additional memory to store the character data and hashing logic. In high-performance scenarios involving millions of records where every millisecond counts, this distinction matters.

If you are building a generic list or an index where keys are purely sequential integers represented as strings (e.g., database IDs returned from a query), you should generally accept the default juggling behavior. It saves memory and leverages CPU cache efficiency. Only switch to explicit string keys if your business logic demands that specific string identity, such as handling codes with leading zeros or ensuring compatibility with external systems that treat 01 and 1 as distinct entities.

Practical Implementation in Laravel

In the Laravel ecosystem, this nuance often surfaces when constructing query scopes or filtering arrays passed to Eloquent. If you are passing a collection of IDs where some are formatted as strings with padding, standard array syntax will collapse them.

// This merges '01' and '1' into the same key
$ids = ['01' => true, '1' => true]; 

// Use braces to preserve distinct keys if needed
$distinctIds = ['{01}' => true, '{1}' => true]; 

When working with Laravel's whereIn or similar query methods, ensure that the type of your key matches the column definition in the database. If a column is defined as VARCHAR, passing an integer might result in implicit casting by the driver, potentially causing mismatches if the database stores leading zeros. Explicitly defining keys with braces ensures you send exactly what you intend to the database layer.

For further insights on array handling and data structures within modern PHP stacks, resources like https://laravelcompany.com provide valuable context on best practices for maintaining data integrity across your application stack.

Our network