How to delete duplicate elements in a PHP array

Source: Internet
Author: User
Our previous article described how to delete headers, tails, arbitrary elements in the PHP array, and this article tells us to delete the repeating elements in the array by using the Array_unique () function.

The Array_unique () function, which sorts the values of an array element as a string, then retains only the first key name for each value, ignoring all subsequent key names, or deleting the repeating elements in the array.

The syntax format is as follows:

Array arry_unique (array array)

The parameter array is an input array.

The following example causes the Array_unique () function to delete the duplicate elements in the array, with the following example code:

<?phpheader ("content-type:text/html; Charset=utf-8 "); $array _push = Array (" topic.alibabacloud.com "," www.php.cn "," www.php.cn "," PHP from Beginner to Proficient ");//define Array Array_ Push ($array _push, "Baidu a Bit", "www.php.cn");//add Element Print_r ($array _push); echo "<br>"; $result =array_unique ($array _ push);//delete duplicate elements in the array print_r ($result); Output the deleted array?>

The output is:

The Array_unique () function applies only to one-dimensional arrays, not to multidimensional arrays, but you can use Array_unique () for values in two-dimensional arrays.

The following example is the use of the Array_unique () function to remove the duplicate elements of a two-dimensional array, the specific code is as follows:,

<?php$array = Array (Array (1,1,2), Array (2,3,4,3));p Rint_r ($array), $temp _array = Array (), foreach ($array as $key = > $value) {    $temp _array[$key] = Array_unique ($value);} $array = $temp _array;echo "<br>";p Rint_r ($array);? >

The output is:

"Related tutorials Recommended"

1. Related topics: "PHP array"

2. Related Video Course recommendation: " array statistics function: count (), Array_count_values () and Array_unique ()"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.