2

I'm using a form with checkboxes. Here is part of the code:

if(isset($_POST['send'])){                          
    $grandezas = array('tempCheckbox', "umiCheckbox", "uvCheckbox", "ventoCheckbox", "direcaoventoCheckbox", "precipitacaoCheckbox");
    $grandezasCount = 0;
    $tamanhoArray = count($grandezas);
    for($i = 1; $i <= $tamanhoArray; $i++){
        if($_POST[$grandezas[i]])
            $grandezasCount++;
        echo $grandezas[i]."."; // This gives me null values.
    }
echo "<br>".count($grandezas)."<br>";
echo $grandezasCount;
printf("%s", $grandezas[1]);

I have the $grandezas array with the names (already checked and they are right) of the checkboxes i used in my form. They return value 1 when checked. All the rest of the form works perfectly fine with a similar logic.

When i use:

echo "<br>".count($grandezas)."<br>";
printf("%s", $grandezas[1]);

It works right, but the echo inside the for loop keeps giving me null values.

Am i using the $_POST[$grandezas[i]] in the wrong way?

1 Answer 1

5

You need to use $i rather than i:

if($_POST[$grandezas[$i]])
        $grandezasCount++;
echo $grandezas[$i].".";

Additionally, checkboxes that are not ticked on the form will not show up in your POST results. This means that you merely need to check that the variable exists IF you know the key is going to be a checkbox:

if( isset($_POST[$grandezas[$i]]) ){
    //checkbox was ticked
}
Sign up to request clarification or add additional context in comments.

1 Comment

Oh my god... Thanks for the help. I'm new to PHP, i constantly forget about this sort of stuff...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.