PHP array_intersect_key() Function

PHP

PHP array_intersect_key() - Intersection by Keys

The array_intersect_key() function in PHP is a powerful tool for comparing arrays based on their keys rather than their values. It returns an array containing the entries from the first array whose keys are present in all other arrays. This function is particularly helpful when you want to identify common keys across multiple arrays regardless of their associated values.

Prerequisites

  • Basic knowledge of PHP arrays
  • PHP installed (version 5.1.0 or higher, as array_intersect_key() was introduced in PHP 5.1.0)
  • Understanding of PHP associative arrays

Setup Steps

  1. Ensure your server environment supports PHP 5.1.0 or later.
  2. Create a PHP fileβ€”for example, array_intersect_key_example.php.
  3. Prepare multiple arrays you wish to compare by keys.
  4. Use array_intersect_key() passing the first array and as many subsequent arrays as you want to compare keys against.

Understanding array_intersect_key() Syntax

array array_intersect_key ( array $array , array ...$arrays )

Returns an array containing all the entries of $array whose keys are present in all the other arrays.

Practical Examples

Example 1: Intersection of Two Associative Arrays by Keys

<?php
$array1 = ['a' => 1, 'b' => 2, 'c' => 3];
$array2 = ['b' => 4, 'c' => 5, 'd' => 6];

$result = array_intersect_key($array1, $array2);

print_r($result);
/* Output:
Array
(
    [b] => 2
    [c] => 3
)
*/
?>

Explanation: Only keys b and c are common to both arrays. The values come from $array1.

Example 2: Intersection with Multiple Arrays

<?php
$array1 = ['x' => 10, 'y' => 20, 'z' => 30];
$array2 = ['w' => 100, 'x' => 200, 'z' => 300];
$array3 = ['x' => 7, 'z' => 8, 'k' => 9];

$result = array_intersect_key($array1, $array2, $array3);

print_r($result);
/* Output:
Array
(
    [x] => 10
    [z] => 30
)
*/
?>

Explanation: The keys x and z are present in all three arrays.

Example 3: Intersection Between Numeric and Associative Arrays

<?php
$array1 = ['apple' => 'red', 'banana' => 'yellow', 'cherry' => 'red'];
$array2 = ['banana' => 'ripe', 'cherry' => 'sweet', 'date' => 'brown'];

$result = array_intersect_key($array1, $array2);

print_r($result);
/* Output:
Array
(
    [banana] => yellow
    [cherry] => red
)
*/
?>

Explanation: Intersection is purely based on matching keys, values do not affect the result.

Best Practices

  • Always ensure the first array (source array) contains the keys and values you want in the result.
  • Use array_intersect_key() when the keys are more important than the values in your comparison logic.
  • Combine with other array functions like array_keys() or array_flip() for advanced key manipulation if needed.
  • When working with large arrays, consider the performance implications of intersecting multiple arrays.
  • Remember that values from only the first array are preserved in the output, values from other arrays are ignored.

Common Mistakes to Avoid

  • Confusing array_intersect_key() with array_intersect(), which compare values instead of keys.
  • Passing non-array types or fewer arguments than expected.
  • Expecting the returned array to include values from all input arrays.
  • Ignoring the fact that the function only compares keys, not values.
  • Not using the function when you need to find matching keys; it can simplify code significantly.

Interview Questions

Junior Level

  1. What does array_intersect_key() do in PHP?
    It returns an array containing entries from the first array whose keys exist in all other passed arrays.
  2. Which part of the arrays does array_intersect_key() compare?
    It compares the keys only, ignoring the values.
  3. What will be the output keys, the keys of which array?
    The keys of the first array passed to the function are preserved in the returned array.
  4. How many arrays can you pass into array_intersect_key()?
    You can pass two or more arrays.
  5. Is array_intersect_key() case-sensitive when comparing keys?
    Yes, PHP array keys are case-sensitive by default.

Mid Level

  1. What happens if keys exist in the second array but not in the first?
    They are ignored; only keys from the first array present in other arrays are returned.
  2. Can array_intersect_key() be used with numeric arrays?
    Yes, but it compares the keys (indices) rather than values.
  3. What is the difference between array_intersect_key() and array_intersect()?
    array_intersect_key() compares keys; array_intersect() compares values.
  4. Does array_intersect_key() preserve the order of keys?
    Yes, it preserves the order of the keys as they appear in the first array.
  5. How can you find keys present in in the first array but not in the second?
    Use array_diff_key() instead of array_intersect_key().

Senior Level

  1. How would you optimize array_intersect_key() on very large arrays?
    Use hash lookups or filters upfront; minimize the number of arrays and keys compared; consider if keys can be indexed for faster lookups.
  2. Is array_intersect_key() stable in preserving key types (string vs int)?
    Yes, it preserves key types and orders as found in the first array.
  3. Can you combine array_intersect_key() with array_map() to manipulate values selectively?
    Yes, you can filter by keys first and then use array_map() to change values accordingly.
  4. How does array_intersect_key() behave with multidimensional arrays?
    It compares only the top-level keys. Nested arrays are considered as values and not recursively compared.
  5. How can you implement a case-insensitive version of key intersection?
    Normalize keys to a common case (e.g., lowercase) using array_change_key_case() before intersecting.

Frequently Asked Questions (FAQ)

Q1: What is the return type of array_intersect_key()?

It returns an array containing all key-value pairs from the first array whose keys appear in every other array.

Q2: Does array_intersect_key() consider array values?

No. It strictly compares keys. Values do not affect the intersection result.

Q3: What happens if no keys match?

An empty array is returned.

Q4: Can I use array_intersect_key() with objects?

No. It only works with arrays. Objects need to be converted to arrays if needed.

Q5: Is the function available in PHP 7+?

Yes, array_intersect_key() is available in all supported PHP versions since 5.1.0 and beyond.

Q6: How do numeric array keys behave?

They are compared as integers. Only indices common to all arrays are retained.

Q7: Can this function modify input arrays?

No. It returns a new array and does not alter the input arrays.

Q8: How is the function different from using array_keys() and array_intersect()?

array_intersect_key() is a direct, efficient function for finding common keys; manually using array_keys() and array_intersect() is more verbose and less efficient.

Q9: Does it preserve keys or reindex the array?

It preserves the original keys from the first array without reindexing.

Q10: Can I use this function to filter an array by another array’s keys?

Yes, this is a common use case to retrieve only elements whose keys are present in other arrays.

Conclusion

The array_intersect_key() function is an essential part of PHP's array toolkit when the goal is to intersect arrays by keys alone. Understanding and leveraging this function allows developers to write cleaner, more efficient code when working with associative arrays or when keys define the structure or relevance of data. Whether for filtering configuration settings, merging data with matching keys, or other use cases, mastering this function enhances your PHP array manipulation skills significantly.