php array_flip()与array_uniqure()删除数组重复元素
在php中删除数组重复元素的函数有几个,一个是array_unique()另外就是array_flip()与array_uniqure()函数,但后者比前者性能要高几倍了,所以我只介绍两者来删除重复数组元素了。
方法如下:
代码如下 | 复制代码 |
$arr = array(…………) ;// 假设有数组包含一万个元素,里面有重复的元素。 |
究竟是怎么回事呢?来看下array_flip()的作用:array_flip()用于将一个数组的每个元素的键和值交换,如:
代码如下 | 复制代码 |
|
在PHP数组中,允许不同的元素可以取同一个值,但不允许同一个键名被不同的元素使用,如:
代码如下 | 复制代码 |
|
这里 $arr1与$arr2 是相等的。
于是,我们便可以知道,为什么 array_flip(array_flip($arr)) 可以删除数组中重复的元素了。首先,$arr里的值会变成键名,因为值是有重复的,变成键名之后这些重复的值便成了重复的键名,PHP 引擎将重复的键名删除,只保留最后一个。如:
代码如下 | 复制代码 |
$arr1 = array("age" => 30, "name" => '快乐园', "age" => 20); |
上面的代码写得简洁一些就是: $arr1 = array_flip(array_flip($arr1));
一些自定的函数
//删除数组中重复元素的函数
代码如下 | 复制代码 |
function delmember(&$array, $id) { $size = count($array); for($i = 0; $i { $array[$id + $i] = $array[$id + $i + 1]; } unset($array[$size - 1]); } |
//使用例子:
代码如下 | 复制代码 |
$output = array(1, 2, 2, 'www.bKjia.c0m', 5, 4, 4, 4, 2, 7, 5, 9, 10); function uniquearray($array) { // get unique elts as keys in assoc. array for ($i=0,$n=count($array, 1);$i $u_array[$array[$i]] = 1;
// copy keys only into another array reset($u_array, 1); for ($i=0,$n=count($u_array, 1);$i $unduplicated_array[] = key($u_array, 1); next($u_array, 1); } return $unduplicated_array; } |

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools