Home Backend Development PHP Tutorial Best way to deduplicate arrays and keep key names in PHP

Best way to deduplicate arrays and keep key names in PHP

May 01, 2024 pm 01:00 PM
Array deduplication form submission Keep key name

There are two best ways to deduplicate arrays and keep key names in PHP: array_unique(): It can deduplicate but not retain key names and re-index the array. Custom function array_unique_preserve_keys(): Use hash values ​​to compare values, which can remove duplicates and preserve key names.

PHP 中对数组去重并保持键名的最佳方法

The best way to deduplicate arrays and keep key names in PHP

In PHP, array deduplication means Remove duplicate values ​​while keeping key names unchanged. This is useful when working with data from different sources that may contain duplicate elements, such as from multiple form submissions or database queries.

Method 1: array_unique()

The array_unique() function is a built-in PHP function used to deduplicate arrays. It accepts an array as input and returns a new array in which duplicate values ​​have been removed. However, array_unique() does not preserve key names, but re-indexes the array, starting at 0.

Example:

$arr = ['a', 'b', 'c', 'c', 'd', 'e', 'a'];

$result = array_unique($arr);

print_r($result); // 输出:['a', 'b', 'c', 'd', 'e']
Copy after login

Method 2: Custom function

To keep the key name, we can write a custom function to deduplicate an array. This method uses an associative array and compares the hash of each value to determine if it is a duplicate.

Example:

function array_unique_preserve_keys($arr)
{
    $hash = [];
    $unique_arr = [];

    foreach ($arr as $key => $value)
    {
        $hash_value = md5($value);
        if (!isset($hash[$hash_value]))
        {
            $hash[$hash_value] = 1;
            $unique_arr[$key] = $value;
        }
    }

    return $unique_arr;
}

$arr = ['a', 'b', 'c', 'c', 'd', 'e', 'a'];

$result = array_unique_preserve_keys($arr);

print_r($result); // 输出:['a' => 'a', 'b' => 'b', 'c' => 'c', 'd' => 'd', 'e' => 'e']
Copy after login

Practical case:

Suppose we have an array from a form submission that contains duplicates Username and email address. By deduplicating it using the array_unique_preserve_keys() function, we can remove duplicate records while maintaining the user's username.

$form_data = [
    ['username' => 'john', 'email' => 'john@example.com'],
    ['username' => 'jane', 'email' => 'jane@example.com'],
    ['username' => 'john', 'email' => 'john@example.org'],
    ['username' => 'mark', 'email' => 'mark@example.net']
];

$unique_users = array_unique_preserve_keys($form_data);

print_r($unique_users); // 输出:['john' => ['username' => 'john', 'email' => 'john@example.com'], 'jane' => ['username' => 'jane', 'email' => 'jane@example.com'], 'mark' => ['username' => 'mark', 'email' => 'mark@example.net']]
Copy after login

The above is the detailed content of Best way to deduplicate arrays and keep key names in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1673
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
How to get form data in layui How to get form data in layui Apr 04, 2024 am 03:39 AM

layui provides a variety of methods for obtaining form data, including directly obtaining all field data of the form, obtaining the value of a single form element, using the formAPI.getVal() method to obtain the specified field value, serializing the form data and using it as an AJAX request parameter, and listening Form submission event gets data.

How to set up jump on layui login page How to set up jump on layui login page Apr 04, 2024 am 03:12 AM

Layui login page jump setting steps: Add jump code: Add judgment in the login form submit button click event, and jump to the specified page through window.location.href after successful login. Modify the form configuration: add a hidden input field to the form element of lay-filter="login", with the name "redirect" and the value being the target page address.

How to implement front-end and back-end interaction in layui How to implement front-end and back-end interaction in layui Apr 01, 2024 pm 11:33 PM

There are the following methods for front-end and back-end interaction using layui: $.ajax method: Simplify asynchronous HTTP requests. Custom request object: allows sending custom requests. Form control: handles form submission and data validation. Upload control: easily implement file upload.

How to build a single-page application using PHP How to build a single-page application using PHP May 04, 2024 pm 06:21 PM

Steps to build a single-page application (SPA) using PHP: Create a PHP file and load Vue.js. Define a Vue instance and create an HTML interface containing text input and output text. Create a JavaScript framework file containing Vue components. Include JavaScript framework files into PHP files.

Specify the basis for removing duplicate elements when deduplicating PHP arrays Specify the basis for removing duplicate elements when deduplicating PHP arrays Apr 28, 2024 pm 10:48 PM

PHP's array_unique() function is used to remove duplicate elements from an array. By default, strict equality (===) is used. We can specify the basis for deduplication through a custom comparison function: create a custom comparison function and specify the deduplication standard (for example, based on element length); pass the custom comparison function as the third parameter to the array_unique() function. Remove duplicate elements based on specified criteria.

The difference between event and $event in vue The difference between event and $event in vue May 08, 2024 pm 04:42 PM

In Vue.js, event is a native JavaScript event triggered by the browser, while $event is a Vue-specific abstract event object used in Vue components. It is generally more convenient to use $event because it is formatted and enhanced to support data binding. Use event when you need to access specific functionality of the native event object.

What is the role of Serverlet in Java What is the role of Serverlet in Java Apr 12, 2024 pm 02:39 PM

Servlet serves as a bridge for client-server communication in Java Web applications and is responsible for: processing client requests; generating HTTP responses; dynamically generating Web content; responding to customer interactions; managing HTTP session state; and providing security protection.

What is the abbreviation of dom in js? What is the abbreviation of dom in js? May 09, 2024 am 12:00 AM

DOM (Document Object Model) is an API for accessing, manipulating and modifying the tree structure of HTML/XML documents. It represents the document as a node hierarchy, including Document, Element, Text and Attribute nodes, which can be used to: access and modify Document structure Access and modify element styles Create/modify HTML content in response to user interaction

See all articles