Scott
Scott

Reputation: 3977

Remove key from array if key is in another array

I have two arrays

array1 (
    "akey1" => "dfksjhf"
    "akey2" => "adasjkgffs"
    "akey3" => "afkjhsafshfkah"
)

array2 (
    "akey2" => "could be anything..."
)

I'm looking for a PHP function that I can supply the two arrays to and the following will happen:

If both arrays have an identical key (regardless of data) then remove the key from array 1 and return the remainder of array 1.

The function if ran would return:

array3 (
    "akey1" => "dfksjhf"
    "akey3" => "afkjhsafshfkah"
)

Is there a PHP function that can do this already and if not what would be the fastest and most efficient way of doing this function in PHP?

Many Thanks

Upvotes: 6

Views: 11055

Answers (2)

user142162
user142162

Reputation:

array_diff_key should work for you:

Returns an array containing all the entries from array1 whose keys are not present in any of the other arrays.

$new_array = array_diff_key($array_1, $array_2);

Upvotes: 4

Felix Kling
Felix Kling

Reputation: 816830

You are looking for array_diff_key():

$array3 = array_diff_key($array1, $array2);

Upvotes: 16

Related Questions