fatkatie Posted January 11, 2018 Share Posted January 11, 2018 (edited) While I'm playing in PHP, this might be better described as a general algorithm request. Here's my problem. I have a reentry page that has numerous post values. In a given set of 7 post values, any 3, and only 3, values must be set. set < 3 || set > 3 == error How would would you code something like that? Do I have to use a loop? Thanks (no - this is not an assignment) Edited January 11, 2018 by fatkatie Quote Link to comment https://forums.phpfreaks.com/topic/306135-any-three-and-only-three-in-a-set-of-n-post-values/ Share on other sites More sharing options...
dodgeitorelse3 Posted January 11, 2018 Share Posted January 11, 2018 echo "<form name='posttest' action='' method='post'><br /> Post 1: <input type='text' name='a[]' value='' /><br /> Post 2: <input type='text' name='a[]' value='' /><br /> Post 3: <input type='text' name='a[]' value='' /><br /> Post 4: <input type='text' name='a[]' value='' /><br /> Post 5: <input type='text' name='a[]' value='' /><br /> Post 6: <input type='text' name='a[]' value='' /><br /> Post 7: <input type='text' name='a[]' value='' /><br /> <input id='tn' type='submit' value='post'> </form>"; echo "<br /><br />"; $countit = 0; foreach($_POST['a'] as $key => $pa) { if(isset($pa) AND !empty($pa)) { $countit++; echo $pa."<br />"; } } if($countit >= 4){ echo "too many post values ($countit)"; } elseif($countit <= 2){ echo "too few post values ($countit)"; } else{ echo "Just right ($countit)"; } 1 Quote Link to comment https://forums.phpfreaks.com/topic/306135-any-three-and-only-three-in-a-set-of-n-post-values/#findComment-1555205 Share on other sites More sharing options...
kicken Posted January 11, 2018 Share Posted January 11, 2018 If your inputs are an array (as demonstrated above), then all you need to do is check if it exists and it's count is 3. $isValid = isset($_POST['selection']) && count($_POST['selection']) == 3; if ($isValid){ echo 'Proper amount selected'; } else { echo 'Invalid selection.'; } 1 Quote Link to comment https://forums.phpfreaks.com/topic/306135-any-three-and-only-three-in-a-set-of-n-post-values/#findComment-1555211 Share on other sites More sharing options...
Barand Posted January 11, 2018 Share Posted January 11, 2018 That would work if they were checkboxes. For text inputs, use array_filter (to remove blanks) before count(). Quote Link to comment https://forums.phpfreaks.com/topic/306135-any-three-and-only-three-in-a-set-of-n-post-values/#findComment-1555213 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.