简体   繁体   中英

Select box option value checked

How to check and find match a select box's value against a series of PHP arrays eg

<select id="person" name="person">
<option value="jane">Jane</option>
<option value="julia">Julia</option>
</select>

PHP arrays

$person_1 = ["Id"=> "1", "name"=>"Jane", "age"=>"23" ]
$person_2 = ["Id"=> "2", "name"=>"Julia", "age"=>"29"]

If user select jane then check the value against these two arrays. If it matches with one print the age of that particular person.

Use a multi-dimensional array so you can loop through it to find the matching name.

$people = [
    ["Id" => "1", "name"=>"Jane", "age"=>"23" ],
    ["Id" => "2", "name"=>"Julia", "age"=>"29"]
];

foreach ($people as $person) {
    if ($person['name'] == $_POST['person']) {
        echo "Age is {$person['age']}";
        break;
    }
}

Any time you find yourself creating variables with numeric names like $person1 and $person2 , it's a sure sign that you should be using an array to collect them all into a single variable.

If there will be lots of people, it would be more efficient to make $people an associative array:

$people = [
    "Jane" => ["Id" => "1", "name"=>"Jane", "age"=>"23" ],
    "Julia" => ["Id" => "2", "name"=>"Julia", "age"=>"29"]
];

Then you don't need a loop, just do:

$person = $people[$_POST['name']];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM