01 · THE IDEAREAD → TRY → LEARN
Why pair arrays?
Data often arrives in parallel lists: one list of names and another of scores, or one of column headings and another of cell values. The lists only mean something when you read them together, so you need a dependable way to join them. Before writing code, decide two things: what shape you want back, and what should happen when the lists have different lengths. A careless pairing routine hides bugs, because a missing value can silently become null or a stray element can be dropped without notice.
Pairing as a keyed map: array_combine()
PHP's built-in array_combine(array $keys, array $values): array uses the values of the first array as keys and the values of the second as the matching values. Use it when the first list really is a set of labels.
$keys = ['green', 'red', 'yellow'];
$values = ['avocado', 'apple', 'banana'];
echo json_encode(array_combine($keys, $values), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), "\n";{"green":"avocado","red":"apple","yellow":"banana"}
The result is a map from each key to its partner. Two properties matter. First, keys that are not valid array keys are converted, so an illegal key value becomes a string. Second, if the same key appears twice, the later entry overwrites the earlier one, so a map can end up shorter than the input.
Mismatched lengths
Since PHP 8.0, array_combine() throws a ValueError when the two arrays have different element counts. Older versions emitted a warning and returned false. Failing loudly is a reasonable policy when a length mismatch means the data is corrupt.
try {
array_combine(['a', 'b'], [1]);
} catch (ValueError $e) {
echo get_class($e), "\n";
}ValueError
Sometimes a mismatch is expected and you simply want to process the part that lines up. That calls for your own function, and the key step is to write the rule down. Here the rule is: pair by position and stop at the shorter array.
A zip function
A zip returns a list of pairs rather than a map, so duplicate left-hand values are all preserved. Each pair is a two-element list [left, right]. Normalising both inputs with array_values() means string keys or gaps in the numeric keys cannot cause undefined-index errors. Then min(count(...), count(...)) gives the number of pairs to build.
function zipShortest(array $left, array $right): array {
$left = array_values($left);
$right = array_values($right);
$count = min(count($left), count($right));
$result = [];
for ($i = 0; $i < $count; $i++) {
$result[] = [$left[$i], $right[$i]];
}
return $result;
}
echo json_encode(zipShortest([1, 2, 3], ['a', 'b']), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), "\n";[[1,"a"],[2,"b"]]
The third element of the first list is ignored because the second list has nothing to match it. That is the documented behavior of this function, not an accident.
A tempting shortcut and its trap
You may know that array_map(null, $a, $b) also builds pairs. It does so by padding the shorter array with null. That is a different policy, and it is dangerous when null is also a legitimate value, because you cannot tell a missing partner from a real null. Choose the policy deliberately instead of inheriting it from whichever function you reached for first.
Edge cases to test
- Two empty arrays produce an empty result.
- A longer left array and a longer right array both truncate to the shorter length.
- Falsy values such as
null,false,0and""are real values and must be paired normally. - Associative input is paired by position, not by key, once
array_values()has run.
Exercise contract
Implement zipShortest(array $left, array $right): array. It must return a list of [left, right] pairs in input order, stop at the shorter array, and return [] when either input is empty. Do not print anything; return the value. The tests compare the returned JSON-compatible structure, including boundary cases where one side is empty-length-different and where values are falsy.
Recap
- Use
array_combine()to build a key-to-value map, and expect aValueErrorfor unequal lengths. - Write a zip function when you want ordered pairs and a clear length policy.
- Normalise with
array_values(), count withmin(), and build pairs with a loop. - Do not let
nullpadding stand in for missing data unless that is your documented choice.
Functions · Arrays · Types
- Pair data safely and define mismatched-length behavior
- Implement and test a deterministic PHP 8.4 function