I have a multi-dimensional array which contains some ID's based on filters a user has chosen to "find" or "exclude" from a search. Each set of filters is grouped by a key (65 in the example below):
$cache_data = ['filters' => [
65 => [
'find' => [
167
],
'exclude' => [
169,
171
]
]
]
];
I want to add some more ID's to the find array whilst retaining any that are already there: 167 in this case. The values in the exclude array need to remain untouched. Assume I want to add the following 4 values to find:
$to_be_added = [241, 242, 285, 286];
I need to target the filters based on their group ID (65 in this case) and merge in my new values using array_merge():
$existing_filters = ($cache_data['filters'][65]);
$merged = array_merge($existing_filters['find'], $to_be_added);
I then rewrite $cache_data['filters'][65] by using $merged with the find key, and keep the values that were already there in exclude:
$cache_data['filters'][65] = [
'find' => $merged,
'exclude' => $existing_filters['exclude']
];
The output for this, print_r($cache_data['filters'][65]); is exactly as I want:
Array
(
[find] => Array
(
[0] => 167
[1] => 241
[2] => 242
[3] => 285
[4] => 286
)
[exclude] => Array
(
[0] => 169
[1] => 171
)
)
However I'm wondering if there is an easier or more efficient way to achieve the same thing?
Using PHP 7.2.10
$cache_data['filters'][65]['find'] += $to_be_added;?+operator will override int keys - I guess OP will not love it...find(167) as well as add the new ones (241, 242, 285, 286).+is not good for youif there is an easier or more efficient way to achieve the same thing?Were you hoping for different ways of writing to do the same? Or perhaps after more performant ways to do the same?