Home > Backend Development > PHP Tutorial > PHP efficiently deduplicates one-dimensional arrays

PHP efficiently deduplicates one-dimensional arrays

不言
Release: 2023-03-22 16:40:01
Original
2106 people have browsed it

本文和大家介绍了关于PHP如何高效率对一维数组进行去重的代码,有需要的朋友们可以参考一下。

$input = array("a" => "green", "red", "b" => "green", "blue", "red");
//常见做法:
$result = array_unique($input);


print_r($result);

Array
(
    [a] => green
    [0] => red
    [1] => blue
)
//效率提升:
/*
 * 第一种
 *  思路:键值互换,达到去重目的,但是结果集中键值可能并不是按照数字索引的,可通过array_merge重新生成索引
*/
$result_01 = array_flip($input);
$result_02 = array_flip($result_01);
$result    = array_merge($result_02);

/*
 * 第二种
 * 思路:键值互换,通过array_key直接获取键值,比array_merge()更快
*/
$result_01 = array_flip($input);
$result    = array_key($result_01);
Copy after login

Related recommendations:

PHP implementation of array deduplication method code

JS array Summary of deduplication methods

The above are the details of how to efficiently deduplicate one-dimensional arrays in PHP. For more information, please pay attention to other related articles on the PHP Chinese website!


The above is the detailed content of PHP efficiently deduplicates one-dimensional arrays. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template