array_intersect_key(): Intersection of two or more arrays considering keys only

This function takes two or more arrays as input and then returns the associative array containing all the keys in input array ( $array1) that are present in all of the arguments.
$new_array = array_intersect_key ($array1, $array2,....);
$array1 : Required , the input array which will be checked.
$array2 : Required , the keys to be matched with $array1.

Here keys are only used for comparison. ( In array_intersect() only values are used for comparison )

Example with two arrays

$first=array('One' =>1,'Two'=>2,'Three'=>3,'Four'=>'Fourth');
$second=array('One'=>1,'Two'=>2,'Third'=>3);

$result1=array_intersect_key($first,$second);
while (list ($key, $val) = each ($result1)) {
echo "$key -> $val <br>";
}
Output is here.
One -> 1 
Two -> 2
Keys of the first index are retained. ( no re-indexing done here) . The third element is not included as the key is different in both arrays.

Example with three arrays

$first=array('One' =>1,'Two'=>2,'Three'=>3,'Four'=>'Fourth');
$second=array('One'=>1,'Two'=>2,'Third'=>3);
$third=array('One'=>1);
$result1=array_intersect_key($first,$second,$third);
while (list ($key, $val) = each ($result1)) {
echo "$key -> $val <br>";
}
Output is here.
One -> 1

Example: Using Associative Arrays

$array1 = ['a' => 'apple', 'b' => 'banana', 'c' => 'cherry'];
$array2 = ['a' => 'avocado', 'b' => 'blueberry'];
$result = array_intersect_key($array1, $array2);
print_r($result);
// Output: Array ( [a] => apple [b] => banana )

Example: Filtering Array by Specific Keys

$array1 = ['name' => 'John', 'age' => 25, 'gender' => 'male', 'country' => 'USA'];
$keys_to_keep = ['name' => '', 'age' => ''];
$result = array_intersect_key($array1, $keys_to_keep);
print_r($result);
// Output: Array ( [name] => John [age] => 25 )

Difference between arrays considering values
Array REFERENCE
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com











    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer