jagav jagav - 1 month ago 6
PHP Question

Best way to reject some elements from array

I have array:

$array = array(
'aaaDSgsdfg' => 3,
'aaaRewrwer' => 4,
'bbbBsdfs' => 1,
'aaaGgfdg' => 4,
'bbbTrtert' => 5
);


How is the best way to reject element with index starting with "bbb"?

I can:

$new = array();
foreach ($array as $index => $element) {
if (substr($index, 0, 2) == 'aaa') {
$new[$index] = $element;
}
}


but maybe is better function for this? Maybe array_map?

Answer

array_filter is what you are looking for:

$array = array_filter($array, function($key) {
   return substr($index, 0, 2) === 'aaa';
}, ARRAY_FILTER_USE_KEY);
Comments