This is what I have:

$prevtag = "1,2,5";

$arr;
$arr["1"] = "BOOKS";
$arr["2"] = "MAGAZINES";
$arr["3"] = "PAMPHLETS";
$arr["4"] = "CD'S";
$arr["5"] = "DVD'S";

And I need to check if any of $prevtag exists in $arr and then echo 5 checkboxes:

foreach ($arr as $key => $value) {
    $checked = in_array($prevtag,$arr) ? '' : 'checked="checked"';
    echo "<input name=\"txtTags".$key."\" type=\"checkbox\" id=\"txtTags".$key."\" value=\"on\" $checked />\n";
    echo "<label for=\"txtTags".$key."\">".$value."</label>\n";
}

But I'm getting all checked and not just the ones in $prevtag - What am I doing wrong?

link|improve this question
You mean key in array? – Shakti Singh Apr 13 '11 at 11:42
feedback

5 Answers

up vote 0 down vote accepted

in_array($prevtag,$arr) is checking if the array $arr contains value 1,2,5

so you can do this:

$checked = in_array($key, explode(',', $prevtag)) ? '' : 'checked="checked"';
link|improve this answer
Perfect! Thanks! – mountainbear Apr 13 '11 at 11:55
feedback
$checked = strpos( $prevtag, (string)$key ) ? '' : 'checked="checked"';

$prevtag is string not array -> in_array() would not apply

link|improve this answer
thanks! - I made it a string – mountainbear Apr 13 '11 at 12:00
feedback

Make $prevtag an array and do something like this

$preArray=explode(",",$prevtag);

foreach ($arr as $key => $value) {
    $checked = in_array($key,$preArray) ? 'checked="checked"' : '';
    ...
}
link|improve this answer
feedback

you are checking if '1,2,5' is inside 'books' or 'magazines' etc

$prevtag = array(1,2,5);
$checked = in_array($key, $prevtag) ? 'checked="checked"' : ''
link|improve this answer
feedback

In your example $prevtag is a string and not an array so you cannot use in_array() on it.

So you can try:

$prevtag = explode(',', $prevtag);

And then:

foreach ($arr as $key => $value) {
    $checked = in_array($key, $prevtag) ? '' : 'checked="checked"';
    echo "<input name=\"txtTags".$key."\" type=\"checkbox\" id=\"txtTags".$key."\" value=\"on\" $checked />\n";
    echo "<label for=\"txtTags".$key."\">".$value."</label>\n";
}
link|improve this answer
thanks - I made it a string – mountainbear Apr 13 '11 at 12:00
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.