Content · Programming · PHP

PHP array_diff_ukey() Function: Usage and Examples

Learn how to use PHP array_diff_ukey() to compare array keys with custom callbacks, find missing entries, and handle case-insensitive comparisons with practical examples.

2 views Published Oct 16, 2026 Updated Oct 16, 2026 Admin

When comparing PHP arrays, you may need to identify keys that exist in one array but not another. Sometimes, however, the default key comparison rules aren't suitable.

For example, an external system might use "Product_ID" while your application expects "product_id".

The array_diff_ukey() function lets you compare array keys using a custom callback, giving you control over which keys are considered equal.

What Is array_diff_ukey() in PHP?

The array_diff_ukey() function compares the keys of one array against the keys of other arrays.

Unlike array_diff_key(), it uses a user-defined callback to determine whether two keys match.

Its syntax is:

array_diff_ukey(
    array $array,
    array ...$arrays,
    callable $key_compare_func
): array

The parameters are:

  • $array — The original array to compare.
  • ...$arrays — One or more arrays to compare against.
  • $key_compare_func — A callback that determines how keys are compared.

The function returns entries from the first array whose keys have no match in the comparison arrays.

Important: Only keys are compared. The associated values do not affect the result.

Example 1: Case-Insensitive Key Comparison

By default, PHP treats "Name" and "name" as different array keys.

Using strcasecmp(), we can compare string keys without distinguishing uppercase and lowercase ASCII letters.

<?php

$first = [
    "Name" => "Alex",
    "Email" => "[email protected]",
    "Role" => "Editor"
];

$second = [
    "name" => "Jordan",
    "email" => "[email protected]"
];

$result = array_diff_ukey(
    $first,
    $second,
    "strcasecmp"
);

print_r($result);

Output:

Array
(
    [Role] => Editor
)

The keys Name and name are considered equal, as are Email and email.

Notice that the values are different, but this doesn't matter because array_diff_ukey() compares keys only.

The Role key has no match, so it remains in the result.

How Does the Comparison Callback Work?

The callback receives two keys and must return an integer:

  • A negative integer if the first key is smaller.
  • 0 if the keys are equal.
  • A positive integer if the first key is greater.

You can create custom comparison rules using an anonymous function.

For example, the following callback treats hyphens and underscores as equivalent:

<?php

$first = [
    "user-name" => "Alex",
    "account-status" => "Active"
];

$second = [
    "user_name" => "Taylor"
];

$compareKeys = static function ($a, $b): int {

    $left = strtolower(
        str_replace("-", "_", (string) $a)
    );

    $right = strtolower(
        str_replace("-", "_", (string) $b)
    );

    return strcmp($left, $right);
};

$result = array_diff_ukey(
    $first,
    $second,
    $compareKeys
);

print_r($result);

Output:

Array
(
    [account-status] => Active
)

The callback converts hyphens to underscores and normalizes capitalization before comparing the keys.

As a result, user-name and user_name are considered equivalent.

The callback must provide consistent comparison results. Avoid returning booleans, which do not correctly represent all three comparison outcomes.

Practical Example: Validating Imported Data Fields

Imagine your application imports product records from an external system.

The application expects three fields, but incoming records may use different capitalization or separators.

We can use array_diff_ukey() to identify missing and unexpected fields.

Create a file named validate-fields.php:

<?php

declare(strict_types=1);

// Fields expected by the application.

$requiredFields = [
    "product_id" => true,
    "product_name" => true,
    "unit_price" => true
];

// Imported record.

$incomingRecord = [
    "PRODUCT-ID" => "P-101",
    "Product-Name" => "Keyboard",
    "quantity" => 5
];

// Define custom key comparison.

$compareKeys = static function ($a, $b): int {

    $normalize = static fn($key): string =>
        strtolower(
            str_replace("-", "_", (string) $key)
        );

    return strcmp(
        $normalize($a),
        $normalize($b)
    );
};

// Find missing required fields.

$missing = array_diff_ukey(
    $requiredFields,
    $incomingRecord,
    $compareKeys
);

// Find unexpected fields.

$unexpected = array_diff_ukey(
    $incomingRecord,
    $requiredFields,
    $compareKeys
);

// Display results.

foreach ($missing as $key => $value) {

    echo "<p>Missing: " . htmlspecialchars(
        (string) $key,
        ENT_QUOTES,
        "UTF-8"
    ) . "</p>";
}

foreach ($unexpected as $key => $value) {

    echo "<p>Unexpected: " . htmlspecialchars(
        (string) $key,
        ENT_QUOTES,
        "UTF-8"
    ) . "</p>";
}

Browser output:

Missing: unit_price
Unexpected: quantity

The application recognizes PRODUCT-ID and Product-Name as equivalent to the expected field names.

However, unit_price is missing, and quantity is an unexpected field.

This technique is useful when importing CSV records, integrating APIs, or checking data structures from external sources.

Note: This example checks field names, not field values. You should still validate required values and their data types separately.

Important Behaviors to Remember

  • Keys only: Values are ignored, even when they differ.
  • Directional comparison: Only unmatched entries from the first array are returned.
  • Original keys preserved: The callback doesn't rename keys in the result.
  • Multiple arrays supported: A key is excluded when a match is found in any comparison array.
  • No recursive comparison: Only top-level array keys are examined.
  • Custom equality rules: Different keys may be considered equivalent, so avoid ambiguous naming conventions that create collisions.

array_diff_ukey() vs Related Functions

Function Comparison Behavior
array_diff_key() Compares keys using PHP's built-in rules.
array_diff_ukey() Compares keys using a custom callback.
array_diff_uassoc() Compares keys using a callback and also compares values.
array_intersect_ukey() Returns entries with matching keys based on a custom callback.

Choose array_diff_ukey() when you only care about key differences and need custom matching rules.

Key Takeaways

  • array_diff_ukey() identifies unmatched array keys.
  • A callback determines how keys are compared.
  • The callback must return a negative integer, zero, or a positive integer.
  • Values are not compared.
  • The function preserves original keys and values in its result.
  • It is useful for comparing records with inconsistent key capitalization or formatting.

The array_diff_ukey() function provides flexible key comparison for PHP arrays. It is especially helpful when integrating external systems that use different naming conventions or when validating the structure of imported data.

For additional details, see the official PHP array_diff_ukey() documentation.

Share this resourceSend this page to someone who may find it useful.