Learn How To Identify The Duplicate Array Using PHP

admin_img Posted By Bajarangi soft , Posted On 16-09-2020

array_unique() function removes duplicate values from an array. If two or more array values are the same than first element will be kept and the other will be removed.

quickly identify duplicates in an array with php

Lets learn,
1.Create array 

$array = array('1' => "apple", '2' => "Strawberries", '3' => "banana", '4' => "apple", '5' => "apple", '6' => "apple", '7' => "kiwi", '8' => "pear", '9' => "pear", '10' => "Mango");


2.Use array_unique() Function.

if values appearance  more than once array_unique method remove duplicates values from an array
 

Syntax of array_unique() function and Usage.

array_unique(array, sorttype)

Parameter Values.
array    -> input array  

sorttype -> its optional, modify the sorting behavior using these Possible values:
                SORT_REGULAR - compare items normally (don't change types)
                SORT_NUMERIC - compare items numerically
                SORT_STRING - compare items as strings
                SORT_LOCALE_STRING - compare items as strings, based on the current locale.


Complete code for quickly find duplicates in an array.

<!DOCTYPE html>
<html>
<head>
    <title>Quickly find duplicates in an array elements</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <div class="text-center">
        <h1>PHP array_unique() Function</h1>
    </div>
    <h3>Quickly find duplicates in an array elements</h3>
    <div class="well">
        <?php
        $array = array('1' => "apple", '2' => "Strawberries", '3' => "banana", '4' => "apple", '5' => "apple", '6' => "apple", '7' =>   "kiwi", '8' => "pear", '9' => "pear", '10' => "Mango");
        print_r(array_unique($array));
        $arr=array_unique($array);
        echo "<br>";
        echo "<br>";
        foreach($arr as $a){// using foreach loop print array elements
            echo $a ."<br>";
        }
        ?>
    </div>
    <br>
</div>
</body>
</html>

Related Post