What Does array_unique Do?

The array_unique function removes duplicate values from an array, keeping only the first occurrence of each value. The function is particularly useful for sanitizing data or working with lists where duplicate entries are undesirable.

Creating a custom implementation of PHP’s array_unique function is an excellent way to understand how unique values can be extracted from an array. This manual method ensures that each value appears only once in the result, preserving the order of the original array.

Below is the PHP code for implementing array_unique without using built-in array functions:

function custom_array_unique($array) {
    $result = []; // Initialize an empty array for unique values.
    $seen = [];   // Initialize an empty array to track seen values.

    foreach ($array as $key => $value) {
        if (!in_array($value, $seen)) { // Check if the value has not been seen before.
            $result[$key] = $value; // Add the value to the result array.
            $seen[] = $value;       // Mark the value as seen.
        }
    }

    return $result; // Return the array with unique values.
}

// Example input array.
$inputArray = ["apple", "banana", "apple", "cherry", "banana", "date"];

// Call the custom function.
$result = custom_array_unique($inputArray);

// Output the result.
print_r($result);

Output:

Array
(
    [0] => apple
    [1] => banana
    [3] => cherry
    [5] => date
)

Explanation

  1. Input Array:
    • The $inputArray contains duplicate values: “apple” and “banana” appear more than once.
  2. Logic:
    • An empty array $seen keeps track of values that have already been added to the result.
    • For each value in the input array, if it hasn’t been seen before, it is added to both $result and $seen.
  3. Result:
    • Only the first occurrence of each value is kept in $result.
    • The keys from the original array are preserved.

Why Create a Custom Implementation?

  • Learning Opportunity: Helps you understand the mechanics of filtering duplicates.
  • Customization: Allows you to modify the logic for more complex scenarios, such as case-insensitive comparisons.
  • Practical Use: Useful in environments where built-in functions are restricted.

Manually implementing the array_unique function without built-in functions is a simple yet powerful exercise. It provides flexibility for customizations, such as case-insensitivity or handling complex data types. This approach is perfect for both learning and solving unique programming challenges.

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *