Checkboxes: Validation & Stickiness

Okay.

No.

So that means you agree with what I was trying to say earlier about the Value could be anything (as long as the Keys are constant)??

Yes.
ON POST you could check the key in a foreach statement against the master array key using

if(array_key_exists($key,$masterlist))

Depending on what you plan on entering into the database, you could also use this $key to get the value from the masterlist array.

You may come to regret it later on in terms of readability when you find yourself wondering “which was Id #10 again?”

1 Like

I think I get Checkboxes enough to be dangerous in the morning! :sunglasses:

Fortunately, I have two other scripts that I can use as cheat-sheets for implementing a lot of this.

My biggest confusion was with how Checkboxes stored entries, but now I see that they are similar to Radio Buttons.

This is a new chapter for me in PHP, but hopefully something I can use more in the future.

Thanks for the help! :thumbsup:

Haaa, someone changed the list order!!!

Okay, that is a valid point!

But how then do I handle the Form?

Can I do something like this…

if (!empty($interest[$interestID])){
    // Checkbox Selected
    // Do Something...

}else{
    // Checkbox Not Selected
    // Do Something Else...
}

(The assumption being that if there is ANY value then the given Checkbox was selected, and if no value exists then the Checkbox wasn’t selected.)

Slight modification to what I posted above. NOTE: I am using $interests as the master list array name. Change as needed.

if(isset($_POST['interest'])):
    
    $cnt=0;
    foreach($_POST['interest'] as $id => $whatever):
        //Validate
        if(array_key_exists($id,$interests)):
            $cnt++;
            //Check count
            if($cnt <= 5):
                //Get the value
                $value = $interests[$id];
                //INSERT to table
                
            endif;
        
        endif;
    endforeach;

endif;

So instead of looping though the main array (100 options) and checking to see if an id was posted, we just loop through posted key/values.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.