Current Location: Home> Latest Articles> Use array_diff_key() and array_filter() to clean up data

Use array_diff_key() and array_filter() to clean up data

M66 2025-05-17

When processing arrays in PHP, we often need to filter and clean up data. Traditionally, we might use loops and conditional judgments to accomplish these tasks, but this practice can lead to bloated and inefficient code. In order to improve the readability and execution efficiency of the code, we can use some built-in array functions, such as array_diff_key() and array_filter() .

This article will introduce how to use these two functions to clean up PHP data and help you write more concise and efficient code.

1. Use array_diff_key() to remove unwanted keys

The array_diff_key() function is used to compare the keys of two arrays, returning an array containing keys that exist in the first array but not in the second array.

Suppose you have an array containing multiple key-value pairs, but you want to remove some unwanted keys. Using array_diff_key() is a good choice. It returns a new array where only the keys you need are retained.

Sample code:

 <?php
// Original array
$data = [
    'name' => 'John',
    'email' => 'john@example.com',
    'phone' => '1234567890',
    'website' => 'https://m66.net'
];

// Keys to be removed
$keysToRemove = ['phone', 'website'];

// use array_diff_key() Remove unwanted keys
$filteredData = array_diff_key($data, array_flip($keysToRemove));

// Output result
print_r($filteredData);
?>

Results output:

 Array
(
    [name] => John
    [email] => john@example.com
)

In this example, array_diff_key() successfully removes the phone and website keys by comparing the keys of the $data array and the $keysToRemove array. array_flip() converts the keys to be removed into the keys of the array and passes them into the array_diff_key() function as the second parameter.

2. Use array_filter() to filter data

The array_filter() function is used to filter elements in an array and return elements that meet the specified conditions. You can use this function to perform more fine filtering of arrays, such as retaining only data that meets a certain condition.

Suppose you have an array that stores data for multiple users and you only want to filter out those valid email addresses, you can use array_filter() to complete this task.

Sample code:

 <?php
// Original array
$users = [
    'user1' => ['name' => 'John', 'email' => 'john@example.com'],
    'user2' => ['name' => 'Jane', 'email' => 'jane@invalid'],
    'user3' => ['name' => 'Mark', 'email' => 'mark@valid.net'],
];

// use array_filter() Filter valid users
$validUsers = array_filter($users, function($user) {
    return filter_var($user['email'], FILTER_VALIDATE_EMAIL) !== false;
});

// Output result
print_r($validUsers);
?>

Results output:

 Array
(
    [user1] => Array
        (
            [name] => John
            [email] => john@example.com
        )

    [user3] => Array
        (
            [name] => Mark
            [email] => mark@valid.net
        )
)

In this example, array_filter() filters those users whose emails are valid through the callback function. Using the filter_var() function, combined with the FILTER_VALIDATE_EMAIL constant, we are able to efficiently verify the email address of each user.

3. Improve code efficiency

Using array_diff_key() and array_filter() can help you improve efficiency when dealing with large arrays. These functions themselves are written in C and are faster than pure PHP loops. At the same time, they can help you write cleaner and easier to read code.

By avoiding manual looping traversal and judgment, you can reduce code complexity, reduce potential errors, and make code easier to maintain.

Summarize

  • array_diff_key() allows you to remove unnecessary keys from the array and keep the data neat.

  • array_filter() helps you filter elements in an array based on conditions, and only elements that meet the conditions are retained.

  • Both functions can improve the efficiency of the code, avoid redundant loops, and make the code more concise and easy to read.

By using these two functions, you can easily process array data, improve your PHP programming skills, and write efficient and easy-to-maintain code.