开发者

PHP FOREACH ARRAY problem

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开发者_JS百科) {
    $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?


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


Make $prevtag an array and do something like this

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

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


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

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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜