Array Keys and Key Conversion

2.Array Keys and Key Conversion

M

In this chapter

We'll learn the rules for array keys: only integers and strings are allowed, how PHP converts other keys — "1" becomes 1, 9.5 becomes 9, true becomes 1 — why a duplicate key overwrites the first value, and how PHP picks the next number when you add an item without a key.

11–13 min

The Problem in Real Life

Mia wants to check "is this slot taken?" in one step, so she keys Saturday's bookings by the hour: $slots[9] = "Tom Hart"; for 9:00, and $slots[9.5] = "Clare Lefèvre"; for 9:30.

She prints the array. There's one entry, key 9, value "Clare Lefèvre". Tom's booking is gone. Above the output, PHP printed something she has never seen: "Deprecated: Implicit conversion from float 9.5 to int loses precision".

M

I booked two customers. Why is only one of them in the array?

Mia

The Key You Write vs. the Key PHP Stores

Keys get converted

PHP stores only integer and string keys. Anything else — a float, a bool, a numeric string — is converted first.

One key, one value

When two keys end up the same, the second value silently replaces the first.

The next number

$a[] = ... picks a key for you. Knowing which one avoids surprises after you remove or mix keys.

Array Keys and Key Conversion

Only two kinds of keys: an array key is always an integer or a string. You can write other things inside the square brackets, but PHP converts them before it stores the value. This chapter covers:

  • Integer and string keys: what each is good for.
  • Key conversion: what happens to numeric strings, floats, bools and null used as keys.
  • Duplicate keys and the next key: why one value can replace another, and which number $a[] = ... uses.

Integer keys: integer keys are positions in a list, or IDs: $barbers[12] = "Ben"; stores Ben under his barber ID, 12. Keys don't have to start at 0 or follow each other — an array can have the keys 12 and 15 and nothing in between. Negative integers work too.

Integer and string keys
<?php
$barbers = [12 => "Ben", 15 => "Leo"]; // keys are barber IDs
$prices = ["Haircut" => 25, "Beard trim" => 10];
echo $barbers[15], "\n"; // Leo
echo $prices["Haircut"], "\n"; // 25
var_dump(isset($prices["haircut"])); // bool(false): keys are case-sensitive

String keys: string keys are names: "time", "customer", "Haircut". They're case-sensitive, so "Time" and "time" are two different keys. Any string works, even one with spaces or an empty string, but simple lowercase names are easiest to read.

Key conversion: here are the rules that removed Tom's booking. A string that is a plain whole number in normal decimal form, like "12", becomes the integer 12 — so $a["12"] and $a[12] are the same item. A string with a leading zero, like "07700900123", or with a decimal point, like "9.5", stays a string. A float key is cut down to a whole number: 9.5 becomes 9, so Clare's booking was written over Tom's. Since PHP 8.1, PHP warns you with a deprecation notice when that loses a fraction. true becomes 1 and false becomes 0. And null becomes the empty string ""; using it is deprecated since PHP 8.5. Arrays and objects can't be keys at all: they cause a TypeError. The table below lists every case.

Table — How PHP converts keys
You writePHP storesNote
$a[12]12An integer: kept
$a["12"]12A plain whole number in a string becomes an integer
$a["07700"]"07700"A leading zero: stays a string
$a["9.5"]"9.5"A decimal point: stays a string
$a[9.5]9A float is cut down; deprecated since PHP 8.1
$a[true] / $a[false]1 / 0Bools become integers
$a[null]""The empty string; deprecated since PHP 8.5
$a[[1]]TypeErrorArrays and objects can't be keys
Mia's bug: 9.5 becomes 9
<?php
$slots = [];
$slots[9] = "Tom Hart"; // 9:00
$slots[9.5] = "Clare Lefèvre"; // 9:30?
print_r($slots);
// Deprecated: Implicit conversion from float 9.5 to int loses precision
// Array
// (
// [9] => Clare Lefèvre
// )
Which keys are converted
<?php
$a = [];
$a["12"] = "string twelve";
$a["07700"] = "leading zero";
$a["9.5"] = "decimal point";
$a[true] = "true";
var_dump(array_keys($a));
// array(4) {
// [0]=>
// int(12)
// [1]=>
// string(5) "07700"
// [2]=>
// string(3) "9.5"
// [3]=>
// int(1)
// }

The fix: use keys that can't collide. For slots, store minutes since midnight as integers (540 for 9:00, 570 for 9:30), which is what Act 06 did, or use the time string itself, "9:30", which stays a string key. Never use a float as a key.

The fix: keys that can't collide
<?php
$slots = [];
$slots[9 * 60] = "Tom Hart"; // 540: minutes since midnight
$slots[9 * 60 + 30] = "Clare Lefèvre"; // 570
foreach ($slots as $minutes => $customer) {
echo sprintf("%d:%02d", intdiv($minutes, 60), $minutes % 60), " ", $customer, "\n";
}
// 9:00 Tom Hart
// 9:30 Clare Lefèvre

Duplicate keys: an array can hold each key only once. Writing to a key that exists replaces its value: $prices["Haircut"] = 25; followed by $prices["Haircut"] = 27; leaves one item, 27. The same happens inside one array literal: ["a" => 1, "a" => 2] is ["a" => 2]. There's no warning; the first value just disappears. After conversion, "1", 1, 1.7 and true are all the same key, 1.

One key, one value: the last one wins
<?php
$prices = ["Haircut" => 25, "Beard trim" => 10, "Haircut" => 27];
print_r($prices);
// Array
// (
// [Haircut] => 27
// [Beard trim] => 10
// )
$same = [1 => "int", "1" => "string", true => "bool"];
print_r($same);
// Array
// (
// [1] => bool
// )

The next key: $array[] = $value; adds a value with the next integer key: one more than the biggest integer key the array has ever had, or 0 if it never had one. In [12 => "Ben"], the next key is 13. String keys don't count. And removing the item with the biggest key doesn't reset the counter, as the next chapter shows.

Which key does $a[] use?
<?php
$barbers = [12 => "Ben"];
$barbers[] = "Leo"; // biggest integer key is 12, so 13
$barbers["owner"] = "Tom";
$barbers[] = "Sam"; // string keys don't count: 14
print_r($barbers);
// Array
// (
// [12] => Ben
// [13] => Leo
// [owner] => Tom
// [14] => Sam
// )

Key Takeaway

Array keys are only integers or strings. PHP converts everything else: "12" becomes 12 (but "07" and "9.5" stay strings), floats are cut to integers (9.5 becomes 9, with a deprecation notice), true becomes 1, and null becomes "" (deprecated in PHP 8.5). Two keys that end up the same are one item, and the last value wins. $a[] uses the biggest integer key so far, plus one.

Why This Matters

Keys are how you find data: a barber by ID, a price by service name, a slot by time. A key that PHP quietly converts into another key can make a booking disappear without an error — in a system whose whole job is not to lose bookings.

Knowing the rules also explains things you'll meet later: why a form field named "12" arrives as key 12, why phone numbers make safe string keys but "12" doesn't, and why IDs from a database keep their meaning as integer keys.

Slots are now keyed by minutes, and both customers are in the array. Then Ann Lee cancels her 10:00 booking. Mia removes it from the day, runs the day view — and gets a warning about key 2 and a missing last booking. That's the next chapter: adding, changing and removing items.