PHP Array Unique

PHP Array Unique

Last Updated on Feb 14, 2023

Array Unique

Array unique removes the duplicate values from an array. In case of a duplication it keeps the first value and removes the rest.


The first argument is the array

And the second argument is a flag to tell php how to compare those values

$array = ['10',10,'pratham','amir','pratham'];
// Array ( [0] => 10 [2] => pratham [3] => amir )

As you can see it has compared '10' and 10 and kept one of them. So let’s see if we can do something to keep both of them because their type is not the same.


We can do that with the help of the second argument. There are flags:

  • SORT_STRING this is the default behavior and compares all the items as string
  • SORT_REGULAR this compares the values without changing their types
  • SORT_NUMERIC this compares the values as numbers
  • SORT_LOCALE_STRING compares items as strings, based on the current locale.

Now all we have to do is to add SORT_REGULAR as the second argument to keep both of the '10' and 10 because their type was not the same. One is string and one is int.

$array = ['10',10,'pratham','amir','pratham'];
print_r(array_unique($array, SORT_REGULAR));
// Array ( [0] => 10 [1] => 10 [2] => pratham [3] => amir )


Now you know about array unique function in PHP.

I recommend you to open a PHP files and try to define an array with duplicated values. then try to remove the duplicates with array unique function.

If you have any suggestions, questions, or opinions, please contact me. I’m looking forward to hearing from you!

Key takeaways

  • remove duplicated values from array with array unique
  • flags for array unique function

Category: programming

Tags: #php #array

Join the Newsletter

Subscribe to get my latest content by email.

I won't send you spam. Unsubscribe at any time.

Related Posts