-2

I have a value like this :

$brands = "1,2,3,4,5"

and I have this :

<input type="checkbox" name="brand[]" value="<?php print"$brand_id"; ?>" /><?php print"$brand_id"; ?>

I want to write source so when $brand_id is one of $brands check box checked means print "checked";

$brands is Variable and write by php

Ebad ghafoory
  • 1,332
  • 3
  • 14
  • 25

3 Answers3

1
<input type="checkbox" name="brand[]" value="<?php echo $brand_id.'" '; echo (in_array($brand_id, $brands))?"checked/>":"/>"; ?>
Babiker
  • 18,300
  • 28
  • 78
  • 125
1
$brands =array("1,2,3,4,5");
<?php foreach($brand as $value){ ?>
<input type="checkbox" name="brand[]" value="<?php echo "$brand_id"; ?>"<?php ($brand_id==$value)?"checked":'';} />
<?php } ?>
K6t
  • 1,821
  • 1
  • 13
  • 21
1

This will output an <input> for every brand you have and append checked="checked" to any of the selected.

$selected = array(2, 5);
$brands = array(1, 2, 3, 4, 5);

foreach ($brands as $brand) {
    echo '<input type="checkbox" name="brand[]" value="'.$brand.'"'.(in_array($brand, $selected) ? ' checked="checked"' : '').'/>'."\n";
}

If the $brands and $selected are dynamic (for example from a MySQL database) you could do something like:

$brands = mysql_fetch_row('SELECT id FROM brand');
$selected = mysql_fetch_row("SELECT brand_id FROM user_brands WHERE user_id = '42'");

But without knowing more about your application, I cannot give a complete answer.

andyb
  • 43,435
  • 12
  • 121
  • 150
  • how i can change array(2, 5) to array($brands) when i do this, just first text box checked – Ebad ghafoory Jun 18 '11 at 12:01
  • @ebad : array(1, 2, 3, 4, 5) is number of brands you have and array(2, 5) is what brand is you selected – Gowri Jun 18 '11 at 12:13
  • i understand but number of brands is dynamic and must get from database and also array(2,5) is dynamic and get from other table in database and may 1,2,3,4,5 changed too 1,4,6,3 or 2,5 change to 1,4,6,3 – Ebad ghafoory Jun 18 '11 at 12:25