Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 623
Scott Avatar asked Mar 24 '11 18:03

Scott


People also ask

How do you delete an element from an array if exists in another array in JS?

You can remove elements from the end of an array using pop, from the beginning using shift, or from the middle using splice. The JavaScript Array filter method to create a new array with desired items, a more advanced way to remove unwanted elements.

How do I remove a key from an array?

Using unset() Function: The unset() function is used to remove element from the array. The unset function is used to destroy any other variable and same way use to delete any element of an array. This unset command takes the array key as input and removed that element from the array.

What is array_keys () used for?

The array_keys() function returns all the keys of an array. It returns an array of all the keys in array.

How do you remove an array from an array?

You can use unset() function which removes the element from an array and then use array_values() function which indexes the array numerically.


2 Answers

You are looking for array_diff_key():

$array3 = array_diff_key($array1, $array2);
like image 53
Felix Kling Avatar answered Oct 26 '22 13:10

Felix Kling


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);
like image 44
Tim Cooper Avatar answered Oct 26 '22 13:10

Tim Cooper