Multiple input fields like
<input type="text" name="row1[]" id="date1">
<input type="text" name="row1[]" id="amount1">
<input type="text" name="row1[]" id="name1">
<input type="text" name="row1[]" id="document1">
Want to check if number of characters in certain fields (not all fields) is at least 1 (in the example do not want to check number of characters in id="document1". Now using this code
if ( (strlen($_POST['row1'][0]) >= 1) or (strlen($_POST['row1'][1]) >= 1) or (strlen($_POST['row1'][2]) >= 1)) ) {
}
Is it possible to shorten code to something like (this is not working code)?
if ( (strlen($_POST['row1']??want_to_check??) >= 1) ) {
}
And input something like (also not working and not real)
<input type="text" name="row1[]??want_to_check??" id="date1">
<input type="text" name="row1[]??want_to_check??" id="amount1">
<input type="text" name="row1[]??want_to_check??" id="name1">
<input type="text" name="row1[]??do_not_want_to_check??" id="document1">
Check number of characters only in certain fields (not all fields)
a tricky shorthand
if (count(array_filter($_POST['row1'],'trim')) != count($_POST['row1'])) {
//not all fields are set
}
but in general, if you see a repetition - you can be sure that a loop can be used. Look:
if ( (
strlen($_POST['row1'][0]) >= 1)
or (strlen($_POST['row1'][1]) >= 1)
or (strlen($_POST['row1'][2]) >= 1)) )
three repeated operators with only counter changing. I am sure you can write a loop for this. Can't you?
Update
Make sensible field names
<input type="text" name="row1[date]" id="date1">
<input type="text" name="row1[amount]" id="amount1">
<input type="text" name="row1[name]" id="name1">
<input type="text" name="row1[document]" id="document1">
Create an array with required field names
$req = array('date1','amount1','name1');
You can loop through fields using foreach
$field_set = false;
if(!empty($_POST['row1'])){
foreach($_POST['row1'] as $key => $row){
//Your code here
if(trim($_POST['row1']))
$field_set = true;
}
}
This will work if you have dynamic number of fields.
Something like this might work
function checkLength($inputs) {
foreach($inputs as $input) {
if(strlen($input) < 1) return false;
}
return true;
}
if(checkLength(array($_POST['input1'], $_POST['input2'], $_POST['input3']))) {
}