Sunday, February 11, 2024

PHP array_merge

The array_merge function in PHP combines the elements of one or more arrays together so that the values of one are appended to the end of the previous one. If an array key exists in both arrays, the value from the second array will overwrite the value from the first array. Example:
$data['product']['desc']['url'] = 'xyz'
$post['desc'] exists, but $post['desc']['url'] does not exist.
$productEdited = array_merge($data['product'], $post)

Since $post['desc'] exists, it will overwrite $data['product']['desc'] in the resulting array. Because $post['desc'] does not have a 'url' key, after the merge, the 'url' key will not exist in the merged array's ['desc'] sub-array because the whole ['desc'] array from $post replaces the ['desc'] array from $data['product'].

To preserve the 'url' key while still merging the rest, you have to:
// Merge top-level arrays
$productEdited = array_merge($data['product'], $post);
// Manually merge 'desc' sub-array, ensuring 'url' is preserved:
$productEdited['desc'] = array_merge($data['product']['desc'], $post['desc']);

No comments:

Post a Comment