-1

I would like to remove all elements of an associative array if the key has a substring of 'TB1' in the key.

My array looks like:

$output= [
       'TB1_course' => 'required'
       'TB1_session' => 'required'
       'TB2_course' => 'required'
    ]

I would like to remove TB1_course and TB1_session, so that my final array looks like:

$output =[
   'TB2_course' => 'required
]

Is there any way to go about doing this in an easy concise fashion?

My initial guess was to use a for each loop:

foreach ($output as $key =>$value){
//remove
}

Thank you for all the help!

Muhammad
  • 604
  • 5
  • 14
  • 29
  • You are expected to try to **write the code yourself**. After [**doing more research**](https://meta.stackoverflow.com/q/261592/1011527) if you have a problem **post what you've tried** with a **clear explanation of what isn't working** and provide [a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). Read [How to Ask](http://stackoverflow.com/help/how-to-ask) a good question. Be sure to [take the tour](http://stackoverflow.com/tour) and read [this](https://meta.stackoverflow.com/q/347937/1011527). – Jay Blanchard Jun 19 '17 at 13:51
  • is this ok `unset($output['TB1_course']); unset($output['TB1_session']);` – LF00 Jun 19 '17 at 13:55

1 Answers1

1

Filter the array by key:

$input = [
    'TB1_course' => 'required',
    'TB1_session' => 'required',
    'TB2_course' => 'required',
];

$filter = function ($key) {
    return substr($key, 0, 4) === 'TB2_';
};

$output = array_filter($input, $filter, ARRAY_FILTER_USE_KEY);

var_dump($output);

Output:

array(1) {
  'TB2_course' =>
  string(8) "required"
}

See http://php.net/array_filter for the documentation of the array_filter function that is useful to filter arrays.

hakre
  • 193,403
  • 52
  • 435
  • 836