Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 44 / 68

Pairing Up Two Arrays (the zip operation)

In this lesson you will learn to pair up two arrays with array_map so related data can be handled together. This is for anyone searching for "PHP array zip".

Combining two corresponding arrays - a list of names and a list of scores, say - into pairs one by one is called a zip operation. Picture matching socks into left-and-right pairs. In PHP you achieve it with array_map(null, ...).

The sample code builds an array of name-and-score pairs with array_map(null, $names, $scores). The key detail is that passing null as the first argument means "do not transform anything, just combine them" - a slightly unusual form.

A common stumbling block for beginners is the idea of passing null as array_map's first argument at all. Normally you pass a transforming function, so without knowing this special behaviour it is easy to be confused.

It is also a frequent choice when you want to loop over several arrays at once. For three or more arrays, just add them to the array_map call.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)