0

I'm currently working on this order form: http://www.libertydelimart.com/order

Right now, all the items get posted to my email - regardless of weather information has been entered into the "How Many" text box.

What is the best way to exclude items that don't have anything entered in the "How Many" text box, so that only the items that do have information entered are emailed to me?

<?php
if(isset($_POST['submit'])) {

$to = "test@mywebsite.com"; 
$subject = "New Order";
$name_field = $_POST['name'];
$phone_field = $_POST['phone'];
$food = $_POST['food'];

$body = 'Name: ' . $name_field . PHP_EOL . 'Phone: ' . $phone_field . PHP_EOL;

//Check if any food items were set in order to prevent foreach error
if($food){
  foreach ($food as $key => $item) {
    $body .= $key . ' - ' . $item ['how_many'];
    if($item['customize']) $body .= ' ('.$item['customize'].')' . PHP_EOL;
  }  
}

echo "Your Order Will Be Ready In 30 Minutes!";
mail($to, $subject, $body,"FROM: Deli <$to>");
print '<pre>'.$body.'</pre>';
}
?>
Abijah
  • 105
  • 3
  • 9

1 Answers1

1

Check if its empty using empty() inside your foreach:

foreach ($food as $key => $item) {
    if (!empty($item['how_many'])) {
        // Add to body only if it isn't empty
        $body .= $key . ' - ' . $item ['how_many'];
        if($item['customize']) $body .= ' ('.$item['customize'].')' . PHP_EOL;
    }
} 

Keep in mind, this doesn't validate whether the input is, in fact, a number. Alternatively, I suggest implementing this SO answer, and check if it is greater than zero.

if ((string)(int)$item['how_many'] == $item['how_many'] && (int)$item['how_many'] > 0)
Community
  • 1
  • 1
Josh
  • 8,082
  • 5
  • 43
  • 41
  • @andrewsi, If the user puts '0' this won't work. You should also check `if (empty($item['how_many']) || $item['how_many']=="0" )` – Sablefoste Aug 23 '12 at 20:22