How to remove this warning Notice: Undefined index:

Asked

Viewed 1,625 times

0

I have a variable $posicoes that receives the amount of elements that exist in the reply session:

$posicoes = count($_SESSION['respostas']);

So I check if the GET idQuestao is greater than the variable positions

if ($_GET['idQuestao'] > $posicoes) {
        // acontece isso... 
} else {
     $voltaQuestao = $idQuestao + 1;
     header("Location: questao.php?idQuestao=" . $voltaQuestao);
}

Dai keeps showing this message every time the variable position is 0

Notice: Undefined index: respostas in C: wamp www quiz questao.php on line 23

Line 23 is this: $posicoes = count($_SESSION['respostas']);

And I need to do this check, it has to start worth 0 anyway. The error message disappears when the variable positions is greater than or equal to 1?

  • Friend format your question better seems a bit confusing ... But if the problem is the message even without error type: error_reporting(0); If you have an error check what is returning in Count and a var_dump in the variable.. Check $_SESSION['replies'] if this correct is minuscule even..

  • Sometimes you solve the problem just by giving a print_r($_SESSION); .

1 answer

1

On the line 23:

$posicoes = isset($_SESSION['respostas']) ? count($_SESSION['respostas']) : 0;

The isset (isset($_SESSION['respostas']), checks whether the variable has been initialized, no longer giving the error described as index is undefined, that is, there is no!

Reference:

  • Thank you very much, you solved my problem, that’s why the ternary operator right?

  • This @Viniciusaquino made a ternary checking if there is a $_SESSION['respostas'] if yes it shows the quantity if it does not assign 0!

Browser other questions tagged

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