Your Location is: Home > Php

Checkbox Using Last Value As First Array

From: United View: 3236 Spywave Noah 

Question

Good Day guys, Please issue on how best to manage my checkbox value in a for loop. first in the form below, people are only to check the Male checkbox if they are male and leave it if the are female. Now my issue is, if the last checkbox is checked, automatically it means only the value of that particular checkbox is set. this makes my php loop to assign it to the first looping data/result. Please how can i rectify this. Thanks in Advance

<form method="Post">

    <input type="checkbox" name="male[]" >
    <input type="text" name="name[]" >

    <input type="checkbox" name="male[]" >
    <input type="checkbox" name="name[]" >

    <input type="checkbox" name="male[]" >
    <input type="checkbox" name="name[]" >

</form>
<?php

$data ="";

    for ($x=0; $x < sizeof($_POST['name']); $x++) {

    $gender = (isset($_POST['male']) ? "Male" : "Female");

    $data .=$_POST['name'][$x].'</br>';

    $data .=$gender.'</br>';

    };

    echo $data;

?>

supposing the last checkbox in the form was checked, the above code outputs,

**Esther** Male
**John** Female
**Mark** Female

Whats happening is its passing the value of the last checked box since it was the only one selected. please how do i manage this

Best answer

When browser submits forms it only submits checkboxes that are checked. And if you use name as male[] the indexes are assigned by php only to data that has been recieved. Thanks to that the $_POST data in your case looks like this:

array( 
    'name' => array(
        0 => 'Esther',
        1 => 'John',
        2 => 'Mark',
    ),
    'male' => array(
        0 => 1
    ),
);

If you want your male array indexes to match the name indexes then you need to define array indexes in the name attribute.

<form method="Post">

    <input type="checkbox" name="male[0]" >
    <input type="text" name="name[0]" >

    <input type="checkbox" name="male[1]" >
    <input type="checkbox" name="name[1]" >

    <input type="checkbox" name="male[2]" >
    <input type="checkbox" name="name[2]" >
</form>

This way even if only checkbox send is the last one, the indexes in array will be kept and the $_POST will look like this:

array( 
    'name' => array(
        0 => 'Esther',
        1 => 'John',
        2 => 'Mark',
    ),
    'male' => array(
        2 => 1
    ),
);

Another answer

You can define the indices of the resulting php array in your html by simply adding the key name between the brackets. (Note that this also works with words, you will end up with an associative array. Do not use quotes in your html.)

<form method="Post">

    <input type="checkbox" name="male[0]" >
    <input type="text" name="name[0]" >

    <input type="checkbox" name="male[1]" >
    <input type="checkbox" name="name[1]" >

    <input type="checkbox" name="male[2]" >
    <input type="checkbox" name="name[2]" >

</form>