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....
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) { ... }
Inside the foreach:
foreach ($_POST as $key => $value) {
if ($key != 'isset') {
//code here
}
}
(For what I got from your question)
Or from your array, you can unset()
the element with the 'isset' array key.