if empty $_POST assign value in foreach loop

后端 未结 5 551
南笙
南笙 2020-12-20 10:57

Hi want to build a program which creates surveys. I couldn\' t figure out how can i assign value for a question which is unanswered. Thank you for your helps.



        
相关标签:
5条回答
  • 2020-12-20 11:00

    $_POST is an associative array So you can access it with:

    $bla = $_POST['bla'];
    

    What you are trying to do is setting the whole array to a string which doesn't work. You should set the new value when saving it to the $dizi array.

    $dizi = array();
    foreach($_POST as $key => $value) {
        $newValue = $value;
        if (empty($value)) {
            $newValue = 'bos';
        }
        $dizi[$key] = $newValue;
        unset($newValue);
    }
    

    But this only checks if answer string is empty. So this only works if all questions are mandatory.

    0 讨论(0)
  • 2020-12-20 11:05

    Try this:

    if(isset($_POST) && (!empty($_POST))){
       foreach ( $_POST as $key => $value ) {
         if(empty($value)){
           $_POST="bos"; 
         } else{
           //put your code
         }
    
       }
     }
    
    0 讨论(0)
  • 2020-12-20 11:12

    If I understood you correctly, what you are trying to do is this:

    foreach ( $_POST as $key => $value ) {
        if(empty($value))
            $_POST[$key] = 'This is an unanswered question!';
    }
    

    But this cannot work due to the fact that empty values aren't posted from the form.

    0 讨论(0)
  • 2020-12-20 11:22

    Your code doesn't make sense, try this:

    $dizi = array();
    foreach($_POST as $key => $value) {
        if (empty($value)) {
            $value = 'your value';
        }
        $dizi[$key] = $value;
    }
    
    0 讨论(0)
  • 2020-12-20 11:25

    How do you know that there is 'unanswered' question if it was not posted from the form? You have to start from the list of the questions (which can not be forged by the user and is defined on the server-side) and check that answer for each of them exists in $_POST. If not - assign whatever you want to the skipped answers.

    0 讨论(0)
提交回复
热议问题