Notice: Undefined offset: 5 in C: xampp htdocs My projects teste2.php on line 10, the value of the arrays being a form value

Asked

Viewed 245 times

-1

I need to write a data chosen by the user, but when not chosen all data appears this message Notice: Undefined offset: 5 in C: xampp htdocs My projects online 10

This is my code:

php test.

<form action="teste.php" method="post">
    <input type="checkbox" name="1" value="1"> 1 <br>
    <input type="checkbox" name="2" value="2"> 2 <br>
    <input type="checkbox" name="3" value="3"> 3 <br>
    <input type="checkbox" name="4" value="4"> 4 <br>
    <input type="checkbox" name="5" value="5"> 5 <br>
    <input type="checkbox" name="6" value="6"> 6 <br>
    <input type="checkbox" name="7" value="7"> 7 <br>
    <input type="checkbox" name="8" value="8"> 8 <br>
    <input type="checkbox" name="9" value="9"> 9 <br>
    <input type="checkbox" name="10" value="10"> 10 <br><br>

    <button type="submit">Enviar</button>
</form>

teste2.php

<?php

$nro_funcoes = 10;

for ($id = 1; $id <= $nro_funcoes; $id++) {
    $nro_funcao[$id] = $id;
}

foreach ($nro_funcao as $func){
    $funcao[$func] = $_POST[$func];
}

$dados = implode(', ',array_filter($funcao));
  • usually the error: Undefined offset happens qnd you try to access a value in an array where it is not present.

1 answer

1


Problem

Checkbox value not sent in POST if not selected.

Solution

Check that the value is set in the $_POST array before using it.

    $nro_funcoes = 10;

    for ($id = 1; $id <= $nro_funcoes; $id++) {
        $nro_funcao[$id] = $id;
    }

    foreach ($nro_funcao as $func) {

        //verificar se está definido

        if (isset($_POST[$func])) {
            $funcao[$func] = $_POST[$func];
        }
    }

    $dados = implode(', ', array_filter($funcao));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.