So I have input fields and when they are submitted, I check to see if their inputted text appears in an array:
<form method="post">
<input type="text" name="1">
<input type="text" name="2">
<input type="text" name="3">
<input type="submit" name="submit">
</form>
<?php
if(isset($_POST['submit'] {
$array = array('432423', '434', '3', '2', '213');
$success = true;
foreach ($_POST as $key=>$value) {
if (!empty($value) && $key != "submit") {
if (!in_array($value, $array)) {
$success = false;
}
}
}
var_dump($success);
// TRUE if all contains, FLASE if any one doesn't contain
}
?>
But if I wanted a certain input field not to have to be checked against the array, how would I do this
Then you probably want to check for another $key != something
?
E.g.
if (!empty($value) && $key != "submit" && $key != "2") {
...
This would exclude the second input...
use https://jqueryvalidation.org
<form id="my_form" method="post">
<input type="text" name="a1">
<input type="text" name="a2">
<input type="text" name="a3">
<input type="checkbox" name="chk1" id="chk1">
<input type="submit" name="submit">
</form>
<script type="text/javascript">
$("#my_form").validate({
rules: {
"a1": {
required: true
},
"a2": {
required: true
},
"a3": {
required: true
},
"chk1": {
required: {
depends: function() {
return !$("#chk1").is(":checked");
}
}
}
}
});
</script>
you can gather all the names in an array just set name="names[]" for the wanted inputs and you will be able to access all the inputs as an array ($_POST['names'])
<form method="post" action="">
<input type="text" name="names[]">
<input type="text" name="names[]">
<input type="text" name="names[]">
<input type="submit" name="submit">
</form>
and loop through them like this
if (! empty($_POST['names']) ) {
$names = $_POST['names'];
foreach ($names as $value) {
if (!empty($value)) {
if (!in_array($value, $array)) {
$success = false;
}
}
}
}