Loop over form values to create a list from deleted items

I’m using the following code too loop over certain form values in order to create a list with deleted items which I need to send to the View:

            $photo         = filter_input(INPUT_POST, 'photo', FILTER_SANITIZE_STRING);
            $name         = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
            $delete_id    = filter_input(INPUT_POST, 'option_id', FILTER_SANITIZE_NUMBER_INT);
            
            $items        = $photo . ' - ' . $name;
            
            foreach($delete_id as $val)
            {
                $items   .= $photo . ' - ' . $name .=  $val."<br>";
                   
            }


            $remove_item  = $this->shop->remove_cart_item($_POST['delete_id']);
            $item_removed = new View('item_removed.php', compact('items'));
            echo $item_removed->render();

It doesn’t give me an error it just gives me the last option. It probably has to do with foreach loop, but what???

Thank you in advance

Is the second “.=” in the loop content confusing things (between $name and $val)? I can never quite get my head around what effect that would have.

It would end up with a string of items separated by <br>'s (also with a dangling br) that… would serve no purpose, really.

It’d depend a lot on what ‘item_removed.php’ (or it’s “View” class) does with the values passed to it.

EDIT: Okay, i’m also blind.

Why is this line outside of your foreach? Why are you using the unfiltered array? Surely you want to one-by-one remove items?

Hi donboe,

$delete_id    = filter_input(INPUT_POST, 'option_id', FILTER_SANITIZE_NUMBER_INT);
$items        = $photo . ' - ' . $name;
foreach($delete_id as $val)
{
    $items   .= $photo . ' - ' . $name .= $val."<br>";
}

I’m guessing that you’re expecting $_POST['option_id'] to be an array, but calling filter_input on it will return false as it is not designed to work with arrays - you need to use filter_input_array for that.

1 Like
$delete_id = filter_input(INPUT_POST, 'option_id', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
2 Likes

As they say, you learn something new every day! Thanks @Pepster :slight_smile:

1 Like

Thanks a lot Pepster and fretburner. I only have a problen in the View (item_removed.php). In that template I have the following. :

<?php foreach ($items as $item){
   echo $item; 
   } ?>

The items are removed I only get the follong error message:

 **Warning: Invalid argument supplied for foreach() in C:\wamp\www\Veldhovenfoto\private\templates\item_removed.php on line 4**

$items is a string, not an array, so it seems you need to remove the foreach loop and just echo $items.

1 Like

Great thanks fretburner. That works perfect. :v: That did the trick indeed. What was I’m thinking

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.