Understanding func_array_unique in PHP

In this article, we will discuss the PHP function func_array_unique. This function removes duplicate values from an array. It returns the unique values in an array, and the original array remains unchanged.

Syntax

The syntax of func_array_unique is:

array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )

array: The input array to filter

sort_flags: The optional sorting flags. The default is SORT_STRING.

Examples

Here are some examples of using func_array_unique.

Example 1

The following example removes the duplicates from the given array:

<?php

$input = array(1, 2, 2, 3, 4, 4);
$result = array_unique($input);
print_r($result);

?>

Output:

Array
(
    [0] => 1
    [1] => 2
    [3] => 3
    [4] => 4
)

Example 2

The following example removes the duplicates from the given associative array:

<?php

$input = array(
    "a" => "apple",
    "b" => "banana",
    "c" => "apple"
);
$result =  array_unique($input);
print_r($result);

?>

Output:

Array
(
    [a] => apple
    [b] => banana
)

Conclusion

In conclusion, array_unique is a useful PHP function that can remove duplicates from an array. Its syntax is straightforward, and it is easy to use. We hope that this article has been helpful to you in understanding array_unique. If you have any questions or comments, please feel free to leave them below.

Practice Your Knowledge

What does the array_unique function in PHP do?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?