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
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.
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.
The array_keys() function returns all the keys of an array. It returns an array of all the keys in array.
You can use unset() function which removes the element from an array and then use array_values() function which indexes the array numerically.
You are looking for array_diff_key()
:
$array3 = array_diff_key($array1, $array2);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With