Merge arrays by suffix of keys PHP

✔ Recommended Answer

If you know the two arrays are the same size, and in the same order, you can use array_combine with array_keys.

$wanted_array = array_combine(array_keys($keys), $submitted_values);

Source: stackoverflow.com

Answered By: Don't Panic

Method #2

To merge two arrays in PHP based on a suffix of their keys, you can use a combination of the array_filter() and array_merge() functions.

Here's an example of how to do this:

php
// Define two arrays to merge $array1 = [ 'name_first' => 'John', 'name_last' => 'Doe', 'email_address' => 'john.doe@example.com', ]; $array2 = [ 'address_street' => '123 Main St', 'address_city' => 'Anytown', 'address_state' => 'CA', 'address_zip' => '12345', ]; // Define the suffix to use for the keys to merge $suffix = '_address'; // Filter the keys in the first array to only include those with the suffix $filteredArray1 = array_filter($array1, function ($key) use ($suffix) { return substr($key, -strlen($suffix)) === $suffix; }, ARRAY_FILTER_USE_KEY); // Merge the filtered array with the second array $mergedArray = array_merge($filteredArray1, $array2); // Combine the merged array with the original array, removing the keys with the suffix $resultArray = array_merge( array_diff_key($array1, $filteredArray1), $mergedArray ); // Output the resulting merged array print_r($resultArray);

In this example, we define two arrays to merge ($array1 and $array2) and a suffix to use for the keys to merge ($suffix). We first filter the keys in the first array to only include those with the suffix, using array_filter() with a callback function that checks if the key ends with the suffix. We then merge the filtered array with the second array using array_merge(). Finally, we combine the merged array with the original array, removing the keys with the suffix using array_diff_key() and merging the result using array_merge(). The resulting merged array contains all the original keys and values, with the values from the second array replacing those from the first array for the keys with the suffix.

Comments

Most Popular

Remove Unicode Zero Width Space PHP

PhpStorm, return value is expected to be 'A', 'object' returned

Laravel file upload returns forbidden 403, file permission is 700 not 755