How to remove duplicate values from PHP array? Explain with example?

Posted by

Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours scrolling social media and waste money on things we forget, but won’t spend 30 minutes a day earning certifications that can change our lives.
Master in DevOps, SRE, DevSecOps & MLOps by DevOps School!

Learn from Guru Rajesh Kumar and double your salary in just one year.


Get Started Now!

In php, array_unique() function is used to remove all the duplicate values from an array, if we have two same values then this function will take first one and removed the another one.

syntax

array array_unique($array, $sort_flags)

this function takes two parameters

  • $array= it specifies the input array from which we want to remove duplicates. it is mandatory
  • $sort_flags= It is optional parameter. This parameter may be used to modify the sorting behavior using these values:

example

<?php
  

$team1 = array("shivam", "abhi", "om", "ravi","shivam","ravi","ram");

$team2 = array("shyam","ram","ramu","ram");
  
  echo "<pre>";
  
print_r(array_unique($team1));

print_r(array_unique($team2));

  echo "</pre>";
?>

output

Array
(
    [0] => shivam
    [1] => abhi
    [2] => om
    [3] => ravi
    [6] => ram
)
Array
(
    [0] => shyam
    [1] => ram
    [2] => ramu
)
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x