WebDevDanno
WebDevDanno

Reputation: 1122

PHP code only prints out first set of values from submitted HTML form

I've got a web form where people can add in a food item and its respective calories. A user is able to click an 'Add' button and add another item as well to create a list. I am then outputting this submitted data into a HTML table. However, the script will only print out the first index of the array.

PHP script

function printFoodTable($food, $kcal) {

    $count = 0;
    $items[] = array('food' => $food, 'kcal' => $kcal);

    foreach($items as $item) {
        echo "<tr>";
        echo "<td>" . $item['food'][$count] . "</td>";
        echo "<td>" . $item['kcal'][$count] . "</td>";
        echo "</tr>";
        $count++;
    }

}

HTML form elements

<input class="item" type="text" name="food[]" placeholder="Item" />
<input class="kcal" type="number" name="kcal[]" placeholder="Kcal" />

If I change $count to 1 for example. The next pair in the array will be printed. So, I know the array is actually being submitted correctly. In the example below it prints out Banana, 120 but if changed it will be Apple, 140 and so on.

Example array

[0] => "Banana", "120" [1] => "Apple", "140" [2] => "Grapes", "230"

Calling the function on form submission

printFoodTable($_POST['food'], $_POST['kcal']);

WORKING SOLUTION Thanks to a brilliant answer. Here is the working code to loop through the submitted values and print them out.

function printFoodTable($food, $kcal) {
    foreach($food as $index => $foodItem) { 
        echo "<tr>";
        echo "<td>" . $foodItem . "</td>";
        echo "<td>" . $kcal[$index] . "</td>";
        echo "</tr>";
    }
}

Upvotes: 1

Views: 258

Answers (1)

billyonecan
billyonecan

Reputation: 20260

The problem you have currently is because of this line:

$items[] = array('food' => $food, 'kcal' => $kcal);

Which will be creating an array within an array (which explains why your loop is only running once). Just change it to:

$items = array('food' => $food, 'kcal' => $kcal);

You don't actually need to create the $items array at all, just foreach over $food or $kcal, pass the array's index as the $key, and use that to get the other array's corresponding value:

foreach ($food as $key => $f) {
  echo $f; // contains current 'food'
  echo $kcal[$key]; // contains corresponding 'kcal'
}

Upvotes: 1

Related Questions