Filter item out of a PHP list

182 views Asked by At

I have a form that currently displays check boxes from a range in an attribute on concrete 5.6. What I need to do is to take that list, but now filter out one item.
I want to filter out mpdID of 81.
The code used to display is:

<div class="clearfix">
    <strong><?php  echo t('Choose Day')?></strong>
    <?php
        if($price_dates){
            foreach($price_dates->dates as $break){
                ?>
                <div class="input">
                    <input type="checkbox" 
                           name="mdpID[]" 
                           value="<?=$break['mdpID']?>" 
                           <?php 
                               if($ticketID['mdpID'] == $break['mdpID']){
                                   echo 'checked';
                               }
                           ?>
                     /> 
                 <?=date('D M jS',strtotime($break['date']))?> - £
                 <?=$break['price']?>
                 </div>

                 <?php
              }
          }
    ?>
</div>
2

There are 2 answers

2
Miura-shi On

You're looking for array_filter

Example

  $mp_ids = [1,5,81,81,23];

  $mp_ids = array_filter($mp_ids, function($value){
    return $value != 81;
  });

If you just do this above the view, then you can keep this logic out of your view and have things a lot cleaner.

A lot of the business logic should be left out of the view, otherwise things will get cluttered fast.

Now $mp_ids will be an array containing any value but 81. You could wrap this into a function to make it more flexible.

Custom Filter Function for IDs

  function filter_ids($array_of_ids, $exclude) {
    return array_filter($array_of_ids, function($value) use ($exclude){
      return $value != $exclude;
    });
  }

  filter_ids($mp_ids, 81);
  // returns array(3) { [0]=> int(1) [1]=> int(5) [4]=> int(23) }
  // return the data to your view to loop and generate the checkboxes

This is just a simple example, and could definitely be improved upon. But should give you an idea on where to go from here to give you more flexibility.

Performance

This would improve your performance on the foreach loop as it's only looping through items that it should output, and not having to constantly check if it should or should not.

0
jayEss On

You can use continue directly after your foreach block begins. Something like this:

foreach block...

if ($break['mdpID'] == 81) {
    continue;
}