1

I'm trying to compare a comma separated string to an arrays keys like I have below, so If they match, I can mark those check boxes as checked.

I'm stuck on this. How can this be done? I can compare two arrays, but I can't think of a way to compare a comma separated string and the keys of an array. Can you help please?

$countries = array (
    "US" => "United States Of America",
    "GB" => "United Kingdom",
    "CA" => "Canada",
    "SE" => "Sweden",
    "AU" => "Australia",
);

$str = 'US,CA,SE'; // This comes from a MySql table

foreach ($countries as $code=>$name) {

    if(//value in comma seperated string == array key i.e US == US) {
        echo '<div><input type="checkbox" name="country[]" value="'.$code.'" checked>'.$name.'</div>'.PHP_EOL;
    } else {
        echo '<div><input type="checkbox" name="country[]" value="'.$code.'">'.$name.'</div>'.PHP_EOL;
    }
}
Norman
  • 6,159
  • 23
  • 88
  • 141
  • 3
    http://stackoverflow.com/questions/3653462/is-storing-a-delimited-list-in-a-database-column-really-that-bad – dm03514 Apr 02 '14 at 15:56

2 Answers2

4
$countries = array (
    "US" => "United States Of America",
    "GB" => "United Kingdom",
    "CA" => "Canada",
    "SE" => "Sweden",
    "AU" => "Australia",
);

$str = 'US,CA,SE';
$selected_countries = explode(',', $str);

foreach ($countries as $code=>$name) {

    if(in_array($code, $selected_countries)) {
        echo '<div><input type="checkbox" name="country[]" value="'.$code.'" checked>'.$name.'</div>'.PHP_EOL;
    } else {
        echo '<div><input type="checkbox" name="country[]" value="'.$code.'">'.$name.'</div>'.PHP_EOL;
    }
}

Here I use explode() to put the three countries in an array. I then find those that match the keys we have in $countries using array_keys() to get those keys and array_intersect() to find the matches. I then compare the keys in $countries against each one we had in our string using in_array().

Emily Shepherd
  • 1,369
  • 9
  • 20
John Conde
  • 217,595
  • 99
  • 455
  • 496
1
$selected_countries = array_flip(explode(',', $str));

foreach ($countries as $code => $name) {
    echo '<div><input type="checkbox" name="country[]" value="'.$code.'" ' . 
        (isset($selected_countries[$code]) ? 'checked' : '') .
        '>'.$name.'</div>'.PHP_EOL;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • There are several errors here. Even when I corrected them, this did not work. `Warning: explode() expects at least 2 parameters, 1 given in C:\web\apache\htdocs\test\checkBoxes.php on line 13 Warning: array_flip() expects parameter 1 to be array, null given in C:\web\apache\htdocs\test\checkBoxes.php on line 13 ` – Norman Apr 02 '14 at 16:14
  • Sorry, left out the delimiter argument to `explode`. – Barmar Apr 02 '14 at 16:15