How to check if value is not NaN in PHP?

I’m trying to make a vote script in PHP but I have some syntax error. I’m a real rocky when it comes to PHP so please be kind…

My “doft” value is NaN if not set?

if ( ! isset(int) $_POST["doft"] ){
    $new_value_doft = $prev_value_doft + $doft;
    $new_num_votes_doft = $prev_num_votes_doft + 1;
}
else{
    $new_value_doft = $prev_value_doft + $doft;
    $new_num_votes_doft = $prev_num_votes_doft; 
}

Related posts

3 comments

  1. The isset method checks if a variable or index is actually set. You want to use it like this

    if( isset( $_POST["doft"] ) ) { }
    

    or, to check if it is not set

    if( !isset( $_POST["doft"] ) ) { }
    

    At the same time, you can make sure/check wether the posted value is an integer like using the is_int method:

    if( isset( $_POST["doft"] )  && is_int( $_POST["doft"] ) ) { }
    

    Or simply use the is_numeric method

    if( isset( $_POST["doft"] )  && is_numeric( $_POST["doft"] ) ) { }
    

    Your given script should probably look like this:

    if ( !isset( $_POST["doft"] ) ){
        $new_value_doft = $prev_value_doft + $doft;
        $new_num_votes_doft = $prev_num_votes_doft + 1;
    }
    else{
        $new_value_doft = $prev_value_doft + $doft;
        $new_num_votes_doft = $prev_num_votes_doft; 
    }
    
  2. Your if statement isn’t working.

    It should look something like this.

    if (!isset($_POST['doft']))

    What you have now isn’t valid, thus the syntax error.

Comments are closed.