Skip to content
Home » Use associative array keys in array_map PHP code examples

Use associative array keys in array_map PHP code examples

Summary

It is impossible to get the array keys in the php array_map function. A good workaround if you need the keys is to use the array_keys function and pass it as an additional array into the array_map function.

Functions Mentioned in this Post

Using Associative Array Keys in PHP array_map

We have already seen the PHP array_map and some important related caveats. In a nutshell, the array_map function applies a callback to every element of the given arrays. One essential quirk of the function is that it passes the values of the given arrays to the callback function. There is no inherent way to pass a key as a parameter to the callback function.

PHP array_map
PHP array_map

In this article, we will see how to use associative array keys in PHP array_map function. To get the most out of this article, we recommend reading our article about array_map PHP.

PHP array_map – Use with associative array keys

Multiple arrays usage – A review

Let’s review the array_map function when it gets more than one array as arguments. This review is crucial because we will be using two arrays to use associative keys in the array_map function.

The example gets two arrays, one consists of Roman numerals, and the other has equivalent numbers spelt out in English. The example uses array_map to get the corresponding values from both arrays simultaneously.

<?php
$roman_numerals = ["I", "II", "III", "IV", "V"];
$english_numbers = ["One", "Two", "Three", "Four", "Five"];
 
print_r(array_map(fn($rom, $eng) => "The Roman Numeral {$rom} is {$eng} in English", $roman_numerals, $english_numbers));
 
/*
OUTPUT
Array
(
    [0] => The Roman Numeral I is One in English
    [1] => The Roman Numeral II is Two in English
    [2] => The Roman Numeral III is Three in English
    [3] => The Roman Numeral IV is Four in English
    [4] => The Roman Numeral V is Five in English
)
*/
?>

Voila! Both these arrays were equal, and the array_map PHP function mapped them using the values from both the arrays. But, what if the two arrays were unequal? Luckily, the function is robust enough to handle them. It pads the shorter array with null values. The following example demonstrates it.

<?php
$roman_numerals = ["I", "II", "III", "IV", "V", "VI"];
$english_numbers = ["One", "Two", "Three", "Four", "Five"];
 
print_r(array_map(fn($rom, $eng) => "The Roman Numeral {$rom} is {$eng} in English", $roman_numerals, $english_numbers));
 
/*
OUTPUT
Array
(
    [0] => The Roman Numeral I is One in English
    [1] => The Roman Numeral II is Two in English
    [2] => The Roman Numeral III is Three in English
    [3] => The Roman Numeral IV is Four in English
    [4] => The Roman Numeral V is Five in English
    [5] => The Roman Numeral VI is  in English
)
*/
?>

The array_map assigns a null value to the missing sixth element of the second array, $english_numbers.

PHP arrays associative keys in PHP array_map function

So, after a quick review of passing multiple arrays arguments to the array_map function, we will extend this idea to pass array keys to the callback function. Since the callback function doesn’t fetch the key, we have to find a workaround.
The idea is to pass the keys as a separate array to the PHP array_map. PHP has a function for separating keys into an array of its own, the array_keys function. So, let’s move on to the example and try out this idea.

<?php
$developers = [
    "Anna" => "Javascript",
    "Edward" => "Java",
    "Rey" => "Python",
    "Sanjay" => "PHP",
    "Ali" => "C++",
    "Sarah" => "C#",
    "Bob" => "Android"
];
 
$dev_names = array_keys($developers);
 
$resultant = array_map(function($name, $tech) {
    return "{$name} is a {$tech} developer";
}, $dev_names, $developers);
 
print_r($resultant);
 
/*
OUTPUT
Array
(
    [0] => Anna is a Javascript developer
    [1] => Edward is a Java developer
    [2] => Rey is a Python developer
    [3] => Sanjay is a PHP developer
    [4] => Ali is a C++ developer
    [5] => Sarah is a C# developer
    [6] => Bob is a Android developer
)
*/
?>

Voila! The idea works like a charm. We had a $developers array with developers names as keys and their skills as values. So, the array_keys isolates the names into a separate array, $dev_names.

The array_map function gets $dev_names, and $developers arrays as arguments, just as we saw in the review section. The callback can fetch the values from both these arrays. This idea is a neat workaround to overcome the inherent limitation of the array_map function.

PHP Fundamentals Recommendations

This article is part of our content on PHP Fundamentals. It includes the core concepts that build upon the foundation of writing high-quality PHP code. If you are looking to grow your PHP development abilities. Check out the following recommended affiliate resources. We do make a commission if you do choose to buy through our links. It is one of the ways that help support our mission here at FuelingPHP.

Book: Fundamentals of Web Development

This book is for you if you are starting to learn how to build websites. It is more than just an “intro to programming” book. You will learn the concepts and tips on what goes into creating a high-quality website. Today’s websites are more than text on a screen. They are highly complex applications that encourage user experience. Learn the fundamentals of good web development with this book.

Check it out on Amazon

Book: Programming in PHP (O’Reilly)

O’Reilly should not need any introduction. They are the top publishers when it comes to books on programming and technology. This book fits well within their vast library. If you are newer to the PHP language or want to keep a solid reference by your side. I highly recommend this book for your collection.

Check it out on Amazon

Book: Design Patterns in PHP

I highly recommend this book to any intermediate-level web developer. It takes the theories and best practices of writing high-quality code via design patterns and applies them to PHP. It is a great resource to take your career to the next level

Check it out on Amazon

Video Course: PHP Fundamentals (Pluralsight)

Want to quickly learn PHP? This PHP Fundamentals course is ideal for beginner PHP developers. It is a deep dive into the concepts, structures and well “fundamentals” of PHP development. It includes high-quality video & interactive resources that teach you really fast. I highly recommend this if you are getting started in your PHP journey.

Click here for a 10-day free trial to Pluralsight

Complete Learning Path: Web Development (Pluralsight)

You should definitely check out this learning path from Pluralsight. They have a huge list of video courses, training, and interactive lessons on growing your web development career. You get access to the full library of hundreds of resources for a single monthly subscription. It truly is like Netflix for your career.

Click here to see details (10-day free trial included)

Using Associative Array Keys in PHP array_map

In this article, we have seen how to use associative array keys in PHP array_map function. The article reviews the use of multiple arrays as arguments in the array_map, followed by the main tutorial of using arrays associative keys in array_map PHP. The example uses the array_keys function to get the array of keys.

Finally, the keys array and the actual array are passed as arguments to the function. Hopefully, this article has been helpful. Stay tuned for more interesting articles and tutorials related to PHP.

Want to explore more useful PHP tutorials?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

How to merge 2 arrays with the same keys in PHP

PHP array_map: How to use in PHP with examples

Difference between array_combine and array_merge in PHP