0

Problem: unwanted empty POST(s) is saved when saving multiple POSTs.

Question: how do I check if an array is empty?

I want to check if the $value[0] is empty and only save the values containing text.

Please feel free to change the code below or use a new example.

foreach ($_POST['bedomning'] as $elevens_id => $value) {

    $ident = $_POST['ident'];   
    $amne_id = $_POST['amne_id'];   
    $datumet = $_POST['datum'];         
    $lararen = $_SESSION['lid'];

    $array_empty = array_filter($value[0]);

    if (!empty($array_empty)){   

        try{    

            $ny_bedomning  = $db->prepare("             
                INSERT INTO `abb_larare` 
                (ident, amne_id, abb_bed_text, elev_id, lid, datum) 
                VALUES (:ident, :amne_id, :abb_bed_text, :elev_id, :lid, :datum) 
            ");                         

            $ny_bedomning->bindParam(':ident', $ident, PDO::PARAM_STR);
            $ny_bedomning->bindParam(':amne_id', $amne_id, PDO::PARAM_INT);
            $ny_bedomning->bindParam(':abb_bed_text', $value[0], PDO::PARAM_STR);
            $ny_bedomning->bindParam(':elev_id', $elevens_id, PDO::PARAM_INT);  
            $ny_bedomning->bindParam(':lid', $lararen, PDO::PARAM_INT); 
            $ny_bedomning->bindParam(':datum', $datumet, PDO::PARAM_STR);       

            $ny_bedomning->execute();   

        }catch(PDOException $e){
        die($e->getMessage());
        }
    }
}
0

1 Answer 1

3

Use empty() to check empty value. Try with -

if (!empty($value[0])) {
   // do staff
}

empty works for -

  • "" (an empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as a float)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • $var; (a variable declared, but without a value)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.