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>";
}
}
$items[] =...asarray( ... );makes the variable an' array.$itemsonly ever has one index in it according to your code. It's a local variable to the function.$foodand$kcalare when used as the parameters to this function. Show all RELEVANT code or we are just guessing$_POSTvariables from the HTML form, hence thefood[]andkcal[]so it would beprintFoodTable($_POST['food'], $_POST['kcal']);when called in the system.foreach ($food as $k => $f) { echo $f; echo $kcal[$k]; }