Jump to content

Recommended Posts

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 by fatkatie

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)";
}
  • Like 1

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.';
}
  • Like 1
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.