using a foreach loop to initialize variables

后端 未结 4 858
抹茶落季
抹茶落季 2021-01-16 08:22

I have built an empty associative array whos keynames refer to submitted post data. I can capture the postdata just fine, but I run into trouble trying to instantiate varia

4条回答
  •  甜味超标
    2021-01-16 09:02

    If I understand you correctly, Im going to suggest this approach:

    $defaultValues = array('rUsername'=>'', 'rPass'=>'', 'rQuestion'=>'', 'rAnswer'=>'', 'rFName'=>'', 'rLName'=>'', 'rBDateD'=>'', 'rBDateM'=>'', 'rBDateY'=>'', 'rHCheck'=>'', 'rHCeckOption'=>'', 'rEmail'=>'');
    $values = array_map('stripslashes', array_merge($defaultValues, array_filter($_POST)));
    extract($values, EXTR_SKIP);
    echo $rUsername;
    echo $rPass;
    .........
    

    By using the snippet above, you have to take into account the following

    • Im using the extract function with EXTR_SKIP so you dont overwrite existing variables. Make sure to only use the variables you need in your code and sanitize them appropietly.

    • By using array_filter on the $_POST superglobal im "erasing" all empty or null variables. so if an expected key was not sent via $_POST, it defaults to the value specified by the $defaultValues array.

    • I dont quite understand why you are using filter_input without the third parameter (filter constants).

提交回复
热议问题