1

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?

0

5 Answers 5

2

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";
}
Sign up to request clarification or add additional context in comments.

Comments

1

Make $prevtag an array and do something like this

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

foreach ($arr as $key => $value) {
    $checked = in_array($key,$preArray) ? 'checked="checked"' : '';
    ...
}

Comments

1
$checked = strpos( $prevtag, (string)$key ) ? '' : 'checked="checked"';

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

Comments

0

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"';

Comments

0

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"' : ''

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.