Reputation: 760
I've an application where at the first page the user is shown four products which he can choose. After he saves the data, I've to show a list of all four products and put a "check" next to the one that the user selected. I'm having trouble with my logic - can anyone help?
// user can choose from these products
$products = array(
'1'=>'Product One',
'2'=>'Product Two',
'3'=>'Product Three',
'4'=>'Product Four' );
// user has choosen these products
$selected_products = explode(',', 'Product One,Product Four');
foreach($selected_products as $product)
{
// Have to print out all products from $products variable, and check
// the ones that the user selected from the $selected_products string.
}
Upvotes: 1
Views: 49
Reputation: 1
$products = array('1'=>'Product One','2'=>'Product Two','3'=>'Product Three','4'=>'Product Four');
// user has choosen these products
$selected_products = explode(',', 'Product One,Product Four');
foreach($products as $id => $p) {
$checked = (in_array($p, $selected_products)) ? 'checked' : '';
echo "<input type='checkbox' name='check' value='{$id}' $checked /> {$p}<br/>";
}
Upvotes: 0
Reputation: 1550
Please make sure the selected products are returned as IDs and not as product names. Then you can use in_array()
to determine whether a checkbox should be checked.
<?php
$products = array(1=>'Product One', 2=>'Product Two', 3=>'Product Three', 4=>'Product Four');
$selectedProducts = array(1,4);
foreach($products as $key => $value) {
$checked = in_array($key, $selectedProducts) ? ' checked' : '';
echo '<input type="checkbox" id="product'.$key.'" value="'.$key.'"'.$checked.' /> <label for="product'.$key.'">'.$value.'</label>';
}
Upvotes: 1
Reputation: 41885
You could use an in_array()
to check whether it is one of the checked choices inside the selected values. Rough example:
$products = array('1'=>'Product One','2'=>'Product Two','3'=>'Product Three','4'=>'Product Four');
// user has choosen these products
$selected_products = explode(',', 'Product One,Product Four');
foreach($products as $id => $p) {
$checked = (in_array($p, $selected_products)) ? 'checked' : '';
echo "<input type='checkbox' name='check' value='{$id}' $checked /> {$p}<br/>";
}
Upvotes: 0