AppDividend
Latest Code Tutorials

PHP array_intersect_key: How to Compare Array Keys

0

PHP array_intersect_key() is an inbuilt function that compares the keys of two (or more) arrays and returns the matches. The function compares the keys of two or more arrays, and return the array that contains the items from array1 that are present in array2array3, etc.

PHP array_intersect_key()

The array_intersect_key() a builtin function in PHP is used to compute an intersection of two or more arrays. The function is different from array_intersect() and array_intersect_assoc() in a way that it uses the keys for the comparison and returns the matching key items. 

The array_intersect_key() returns an array containing all the entries of array1 which have keys that are present in all the arguments.

Syntax

See the following syntax.

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

Parameters

The array1 parameter is required, and the first array is the array that the others will be compared with.

The array2 parameter is required and an array to be compared with the first array.

The array3 is optional and the array to be compared with the first array.

Compare the keys of two indexed arrays

See the code.

<?php

$a1 = array("eleven", "dustin", "will", "nancy");
$a2 = array("mike", "lucas", "steve");

$result = array_intersect_key($a1, $a2);
print_r($result);

See the output.

➜  pro php app.php
Array
(
    [0] => eleven
    [1] => dustin
    [2] => will
)
➜  pro

We get the three items because array $a1 and $a2 have same index 0, 1, 2. So it will return the first three items because of three indexes of $a1 match with $a2.

Compare the keys of three arrays

See the following code.

<?php

$a1 = array("eleven", "dustin", "will", "nancy");
$a2 = array("mike", "lucas", "steve");
$a3 = array("hopper", "jonathan", "joyce", "jonathan");

$result = array_intersect_key($a1, $a2, $a3);
print_r($result);

See the following output.

➜  pro php app.php
Array
(
    [0] => eleven
    [1] => dustin
    [2] => will
)
➜  pro

Compare the Associative Array keys

See the following code.

<?php

$a1 = array("eleven" => 11, "dustin" => 21, "will" => 30, "nancy" => 40);
$a2 = array("mike" => 12, "lucas" => 20, "eleven" => 11);
$a3 = array("eleven" => 11, "jonathan" => 35, "joyce" => 10);

$result = array_intersect_key($a1, $a2, $a3);
print_r($result);

See the output.

➜  pro php app.php
Array
(
    [eleven] => 11
)
➜  pro

In the above code, eleven is the only key that is there in all three arrays; that is why it gives eleven in output.

If eleven key was not there in even in one array, then an empty array will be returned.

Finally, PHP array_intersect_key() Function Example is over.

Recommended Posts

PHP array_fill_keys()

The array_udiff() Method In PHP

PHP array_reduce()

PHP Array Flip

PHP array_walk()

Leave A Reply

Your email address will not be published.

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