SamB. SamB. - 1 month ago 14
PHP Question

PHP for loop count from select list

I am working on a project and am still relatively new to PHP. I am attempting to run a for loop which counts the number of times each flower is selected from a select list off of an HTML page. I am continuously getting "1" for all 3 flower types after choosing different combinations from the select lists during testing. If anyone has any input as to where my mistakes are I would greatly appreciate it! Here is my HTML code:

<html>
<head>
</head>
<body>
<h1>FLOWERS</h1>
<form action = 'php 08.php' method = 'post'>

<select id = '0' name = '0'>

<option value = 'marigold'>marigold</option>
<option value = 'rose'>rose</option>
<option value = 'tulip'>tulip</option>

</select>

<br><br>

<select id = '1' name = '1'>

<option value = 'marigold'>marigold</option>
<option value = 'rose'>rose</option>
<option value = 'tulip'>tulip</option>

</select>

<br><br>

<select id = '2' name = '2'>

<option value = 'marigold'>marigold</option>
<option value = 'rose'>rose</option>
<option value = 'tulip'>tulip</option>

</select>

<br><br>

<select id = '3' name = '3'>

<option value = 'marigold'>marigold</option>
<option value = 'rose'>rose</option>
<option value = 'tulip'>tulip</option>

</select>

<br><br>

<select id = '4' name = '4'>

<option value = 'marigold'>marigold</option>
<option value = 'rose'>rose</option>
<option value = 'tulip'>tulip</option>

</select>

<br><br>

<input type = 'submit' id = 'go' value = 'COUNT'>

</form>
</body>
</html>


Here is my PHP code:

<?php

$marigold = $_POST['marigold'];

$rose = $_POST['rose'];

$tulip = $_POST['tulip'];

for ($i = 0; $i <= 4; $i++) {

if ($i == 'marigold') {

$marigold++;

};

if ($i == 'rose') {

$rose++;

};

if ($i == 'tulip') {

$tulip++;

};

};

echo "MARIGOLD <span id = 'marigold'>$marigold</span>";

echo "<br><br>";

echo "ROSE <span id = 'rose'>$rose</span>";

echo "<br><br>";

echo "TULIP <span id = 'tulip'>$tulip</span>";

?>

Answer

If you want to keep your HTML like this, your PHP code should be like that:

//Initialise your counter
$marigold=$rose=$tulip=0

for ($i = 0; $i <= 4; $i++) {

    if ($_POST[$i] == 'marigold') {
        $marigold++;
    }

    if ($_POST[$i] == 'rose') {
        $rose++;
    }

    if ($_POST[$i] == 'tulip') {   
        $tulip++;    
    }

}

echo "MARIGOLD <span id = 'marigold'>$marigold</span>";

echo "<br><br>";

echo "ROSE <span id = 'rose'>$rose</span>";

echo "<br><br>";

echo "TULIP <span id = 'tulip'>$tulip</span>";