jagav
jagav

Reputation: 23

Best way to reject some elements from array

I have an array:

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

Which 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?

Upvotes: 2

Views: 1039

Answers (3)

icoder
icoder

Reputation: 165

You can use array_filter() function:

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

Upvotes: 0

iainn
iainn

Reputation: 17417

If you're using PHP 5.6+, you can use array_filter to achieve this:

$array = array_filter(
  $array,
  function ($e) { return strpos($e, 'bbb') !== 0; },
  ARRAY_FILTER_USE_KEY
);

See https://eval.in/669810

Upvotes: 2

krasipenkov
krasipenkov

Reputation: 2029

array_filter is what you are looking for:

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

Upvotes: 1

Related Questions