doumu9019 2012-11-10 16:04
浏览 131
已采纳

如何从PHP foreach循环中排除隐藏字段

I have a simple form that inserts data into a database using foreach($_POST as $key=>$value) I have a hidden field on the form

<input name="isset" type="hidden" value="true" />

And i use if(isset($_POST['isset'])) {

I'm trying to work out how to exclude the hidden field from the loop ...?

I've looked at this post but don't understand where i would use if (strpos($key, 'hdn_') == false) // proceed

How to exclude <input type="hidden"> from a for each loop in PHP

any guidance would be appreciated....

  • 写回答

2条回答 默认 最新

  • dongxie3701 2012-11-10 16:12
    关注

    If you know the exact names of keys you want to exclude, array_diff_key is a convenient option:

    $keysToRemove = array('isset'); // you can add as many as you want
    $values = array_diff_key($_POST, array_flip($keysToRemove));
    
    foreach ($values as $k => $v) { ... }
    

    However, since $values is intended to go into the database you should use a whitelist of allowed keys instead of a blacklist. You can do that with array_intersect_key:

    $keysToKeep = array('field1', 'field2', 'field3'); // as many as you want
    $values = array_intersect_key($_POST, array_flip($keysToKeep));
    
    foreach ($values as $k => $v) { ... }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?