Special Anniversary Black Friday: Get 30% off all training and 10% off all services Get a Quote


Optimize Your PHP Code: 8 Functions You Need for Efficient Table Handling

· Imen Ezzine · 3 minutes to read
Blue ElePHPant on a computer

If you want to become a good PHP developer, you must learn to work with arrays. Arrays are used a lot in PHP: temporarily store, organize, and process data before it's saved in a database. Knowing how to work with them efficiently will help you manage and process data more effectively.

In this article, we'll look at eight important functions for working efficiently with arrays in PHP. These functions will help you improve your code and solve difficult problems more easily.

1. array_map

The array_map function applies a given function to each element of one or more arrays and returns an array containing the results. Note that the keys of the original arrays are not affected: they are retained in the resulting array, even if the values are modified.

Example:

$numbers = [1, 2, 3, 4];
$squaredNumbers = array_map(function($n) {
  return $n * $n;
}, $numbers);

print_r($squaredNumbers); 
// Résultat : [1, 4, 9, 16]

💡 Tip: If you don't need to create a new array, but simply want to modify the existing one, you can use array_walk. array_walk applies a function to each element of the array but modifies the array directly, without returning it. This can be more efficient in some cases.

Example with array_walk:

$numbers = [1, 2, 3, 4];
array_walk($numbers, function(&$n) {
    $n *= $n;
});
print_r($numbers);
// Résultat : [1, 4, 9, 16]

As you can see, 'array_walk' directly changes the $numbers array without making a new one.

2. array_reduce

The array_reduce function is used to find a single total by applying a callback function to each element of an array. The "value" that it produces can be of any type, including array, string, or object. The type of value it produces depends on the logic defined in the callback

Example:

$numbers = [1, 2, 3, 4];
$sum = array_reduce($numbers, function($carry, $item) {
. return $carry + $item;
}, 0);

echo $sum; 
// Résultat : 10

3. array_filter

The array_filter function filters the elements of an array based on a callback function. Only the elements that return true will be included in the returned array. The callback function can also accept the key of each element. This allows filtering not only by value but also by key.

If you need more information, check the official documentation on array_filter with mode.

Example:

$numbers = [1, 2, 3, 4, 5];
$evenNumbers = array_filter($numbers, function($n) {
. return $n % 2 === 0;
});

print_r($evenNumbers); 
// Résultat : [2, 4]

4. array_merge

The array_merge function combines one or more arrays into a single one. This function is used to merge several data sets.

Example:

$array1 = ["a" => "pomme", "b" => "banane"];
$array2 = ["a" => "ananas", "c" => "citron"];
$result = array_merge($array1, $array2);

print_r($result);
// Résultat : ["a" => "ananas", "b" => "banane", "c" => "citron"]

5. array_keys

The array_keys function returns all the keys of an array or the keys that correspond to a specified value. It's particularly useful for getting the indices from associative arrays.

Example:

$array = ["a" => "pomme", "b" => "banane", "c" => "citron"];
$keys = array_keys($array);

print_r($keys); 
// Résultat : ["a", "b", "c"]

However, to check whether a key exists in an array, it's better to use array_key_exists than to get all the keys with array_keys and then use in_array. Using array_key_exists is more direct and avoids unnecessary steps 🚀

$array = ['nom' => 'Jean', 'âge' => 30];

if (array_key_exists('nom', $array)) {
    echo 'La clé "nom" existe dans le tableau';
}

6. array_values

The array_values function returns all the values in an array. I suggest using it when you want to get an array of numbers from another array.

Example:

$array = ['a' => 'pomme', 'b' => 'banane', 'c' => 'citron'];
$values = array_values($array);

print_r($values); 
// Résultat : ['pomme', 'banane', 'citron']

7. array_unique

The array_unique function gets rid of duplicate values in an array. This function is useful for getting a set of different values.

Example:

$array = ['pomme', 'banane', 'pomme', 'citron'];
$uniqueArray = array_unique($array);

print_r($uniqueArray); 
// Résultat : ['pomme', 'banane', 'citron']

8. array_combine

The array_combine function creates an array by combining two different arrays. One array has the keys, and the other has the values. Each key in the first array will be linked to a value in the second array. This makes it useful for combining two sets of data, like names and ages.

Example:

$keys = ['nom', 'prénom', 'âge'];
$values = ['Dupont', 'Jean', 30];

$resultat = array_combine($keys, $values);

print_r($resultat);
// Résultat :
// Array
// (
//     [nom] => Dupont
//     [prénom] => Jean
//     [âge] => 30
// )

Conclusion

Knowing how to change arrays is a basic skill for any PHP developer. If you learn these functions, you'll be able to work with data more efficiently and write cleaner, more maintainable code. Whether you're transforming, filtering, merging, or reducing arrays, these tools are essential for solving the day-to-day problems you'll face in your projects. Take the time to understand how they work and add them to the tools you use every day.

You can find more information about array functions and learn more about PHP on the official documentation website: https://www.php.net/manual/en/ref.array.php. There, you'll find a list of all the functions available for working with arrays, along with examples and explanations.

Need expert help with your PHP code optimization?

The experts at SensioLabs, the creator of Symfony, the leading PHP framework, will help you strengthen your PHP code.

This might also interest you

PHP 8.5 URI extension
Oskar Stark

PHP 8.5's New URI Extension: A Game-Changer for URL Parsing

PHP 8.5 introduces a powerful new URI extension that modernizes URL handling. With support for both RFC 3986 and WHATWG standards, the new Uri class provides immutable objects, fluent interfaces, and proper validation - addressing all the limitations of the legacy parse_url() function. This guide shows practical before/after examples and explains when to use each standard.

Read more
Open in new tab
Silas Joisten

The Tab Trap: Why Forcing New Tabs Is Bad UX

We’ve all done it — added target="_blank" to a link to “help users” stay on our site. But what feels like a harmless convenience often creates confusion, breaks accessibility, and introduces hidden security risks.

Read more
3 dog heads
Mathieu Santostefano

Bring Your Own HTTP client

Break free from rigid dependencies in your PHP SDKs. Learn how to use PSR-7, PSR-17, and PSR-18 standards along with php-http/discovery to allow users to bring their favorite HTTP client, whether it's Guzzle, Symfony HttpClient, or another. A must-read for PHP and Symfony developers.

Read more
Blue sign on a building with several Now What? letters
Thibaut Chieux

How To Prioritize Messages When Building Asynchronous Applications With Symfony Messenger

Asynchronous processing offers benefits like decoupled processes and faster response times, but managing message priorities can become a challenge. When dealing with tasks ranging from password resets to complex exports, ensuring timely delivery of critical messages is essential. This article explores common asynchronous processing issues and provides solutions using Symfony Messenger, allowing you to optimize your application without extensive refactoring.

Read more
PHP 8.5
Oskar Stark

What's New in PHP 8.5: A Comprehensive Overview

PHP 8.5 will be released in November 2025 and brings several useful new features and improvements. This version focuses on developer experience enhancements, new utility functions, and better debugging capabilities.

Read more
Two images: on the left many cars stuck in a traffic jam with the sign "All directions" above, on the right a blue car moving forward alone on the highway with the sign "Service Subscriber" and a Symfony logo above
Steven Renaux

Symfony Lazy Services with Style: Boost DX using Service Subscribers

Boost your Symfony app's performance and developer experience! Learn how to use Service Subscribers and traits for lazy service loading to reduce eager instantiation, simplify dependencies, and create modular, maintainable code.

Read more
the surface of the earth seen from the space with city lights forming networks
Imen Ezzine

HTTP Verbs: Your Ultimate Guide

HTTP Verbs Explained: Learn the basics of GET, POST, PUT, DELETE, and more. This article explains how they work, their applications, and their security implications.

Read more
Domain Driven Design practical approach
Silas Joisten

Applying Domain-Driven Design in PHP and Symfony: A Hands-On Guide

Learn how to apply Domain-Driven Design (DDD) principles in Symfony with practical examples. Discover the power of value objects, repositories, and bounded contexts.

Read more
Photo speaker meetup AI Symfony
Jules Daunay

Symfony and AI: the video is now available

What about Symfony and Artificial Intelligence (AI)? This was the theme of the exclusive event organized by SensioLabs in partnership with Codéin on October 3rd. With the added bonus of feedback from a development project combining Symfony and AI. If you missed the event, check out the video now available for free on our Youtube channel.

Read more
2025 a year of celebrations for PHP with windows about API Platform, PHP, AFUP and Symfony
Jules Daunay

2025: a year of anniversaries for PHP, AFUP, Symfony and API Platform

2025 is going to be a big year for anniversaries. We will be celebrating the 20th anniversary of Symfony, the 30th anniversary of PHP, the 25th anniversary of AFUP and the 10th anniversary of API Platform. For SensioLabs, this is a major milestone that proves the longevity of the technologies in our ecosystem. We are proud to celebrate these anniversaries with the community all year long.

Read more
Grey Cargo Plane with a Blue Sky
Rémi Brière

Agility and the Cargo Cult - Part 1

Agility is more than just rituals and tools. In this first article of our Scrum series, we explore the Cargo Cult phenomenon and how blind imitation can hinder true Agile transformation.

Read more
SemVer vs. CalVer
Silas Joisten

SemVer vs. CalVer: Which Versioning Strategy is Right for You?

SemVer ensures stability for libraries, while CalVer aligns projects with release cycles. Learn the key differences and best use cases to optimize your versioning strategy.

Read more
Image of a desk with a laptop and monitor
Oskar Stark

Introducing PIE: The Modern PHP Extension Installer

Discover PIE, the new PHP Installer for Extensions, a modern tool that simplifies managing PHP extensions with a Composer-like workflow. Say goodbye to PECL complexities and streamline your development process with PIE.

Read more
DDD
Silas Joisten

Understanding Domain-Driven Design: A Practical Approach for Modern Software Architecture

Explore Domain-Driven Design (DDD) principles and patterns like Ubiquitous Language, Aggregates, and Bounded Contexts. Learn how DDD fits seamlessly into PHP and Symfony projects, helping you align software with business needs.

Read more
SymfonyLive 2024
Jules Daunay

SymfonyLive Paris 2024: Two Days of Conference and Fun.

On March 28th and 29th, the SensioLabs team and the French-speaking Symfony community gathered at the Cité Internationale Universitaire in Paris for SymfonyLive Paris 2024. Were you not at this must-attend event? We’ll summarize it for you, but only because it’s you!

Read more
Image