Share this:

Working with arrays is a common task in PHP development. Sometimes, we may have a multidimensional array with duplicate values that we need to remove.

In this blog post, we’ll explore a simple PHP function that can help you remove duplicate values from a multidimensional array.

How to remove duplicate values from multidimensional array in PHP?

To remove duplicate values from a multidimensional array, we can use the built-in PHP function array_map() and array_unique(). The array_map() function applies a given callback function to each element of an array and returns a new array with the modified elements. The array_unique() function removes duplicate values from an array. Here’s an example of how to use them together:

$multi_array = array(
    array("id" => 1, "name" => "John"),
    array("id" => 2, "name" => "Jane"),
    array("id" => 1, "name" => "John"),
    array("id" => 3, "name" => "Joe")
);

$unique_array = array_map("unserialize", array_unique(array_map("serialize", $multi_array)));

In this example, we first define a multidimensional array $multi_array that contains duplicate values. We then use array_map() with the serialize() function to convert each element of $multi_array into a string. We apply array_unique() to the resulting array to remove duplicate strings, and then use array_map() with the unserialize() function to convert each string back into an array. The resulting $unique_array is a new array that contains only unique elements.

It’s important to note that this method only works with simple multidimensional arrays that do not contain objects or resources. If your multidimensional array contains objects or resources, you will need to use a different method to remove duplicate values.

Conclusion:

Removing duplicate values from a multidimensional array is a common task in PHP development. Fortunately, PHP provides built-in functions like array_map() and array_unique() that can help us achieve this easily. By using the examples above, you should now be able to remove duplicate values from any multidimensional array in your PHP code. If you have any questions or comments, please leave them below.

If you found this blog post helpful, please consider sharing it on social media or leaving a comment below. Also, feel free to check out our other PHP tutorials and resources on our website.

Share this:

Categorized in: