PHP array_intersect_key() Function

PHP array_intersect_key() function is used to compare the keys of two or more arrays, and returns an array containing the entries of the first array which have keys that are present in all the other arrays.

Syntax

array_intersect_key($array1, $array2, $array3, ...)

Parameters

  1. $array1(required): The first array is the array that the keys are going to be checked on.
  2. $array2(required): The array to compare against the first array.
  3. $array3(optional): More arrays to compare against the first array.

    In PHP 8.0.0, this function can be called with only one parameter.

    Return value

    It returns an associative array containing all the entries of array1, that are present in all of the other arrays.

    Visual RepresentationVisual Representation of PHP array_intersect_key() FunctionExample 1: How to Use array_intersect_key() Function

    <?php
    
    $arrA = [
     'a' => 'AppDividend',
     'b' => 'Hermès',
     'c' => 'Gucci'];
    
    $arrB = [
     'x' => 'Meta',
     'y' => 'Yahoo',
     'c' => 'Google'];
     
    $result=array_intersect_key($arrA,$arrB); 
    print_r($result);

    Output

    Array
    (
     [c] => Gucci
    )

    In this example, the array_intersect_key() function returns the key ‘Gucci‘ that is present in both $arrA and $arrB.

    Example 2: Comparing the keys of three arraysVisual Representation of Comparing the keys of three arrays

    <?php
    
    $arrA = [
     'a' => 'AppDividend',
     'b' => 'Hermès',
     'c' => 'Gucci'];
    
    $arrB = [
     'x' => 'Meta',
     'a' => 'Google',
     'y' => 'Yahoo'];
     
    $arrC = [
     'y' => 'Apple',
     'a' => 'Amazon']; 
     
    $result=array_intersect_key($arrA,$arrB, $arrC); 
    print_r($result);
    

    Output

    Array
    (
     [a] => AppDividend
    )
    

    Example 3: Comparing the keys of two indexed arraysVisual Representation of Comparing the keys of two indexed arrays

    <?php
    
    $a1 = ["eleven", "dustin", "will", "nancy"];
    $a2 = ["mike", "lucas", "steve"];
    
    $result = array_intersect_key($a1, $a2);
    print_r($result);
    

    Output

    Array ( 
     [0] => eleven 
     [1] => dustin 
     [2] => will 
    )
    

    That’s it.

    Leave a Comment

    This site uses Akismet to reduce spam. Learn how your comment data is processed.