swett.bp
swett.bp

Reputation: 313

Get explode data to show in checkbox with others data

I have string data in database table('fruit_select') like this

$fruit = "apple,orange,banana";

and i need to get all fruits in database table('fruits') like this

$all_fruits = array('apple','banana','kiwi','melon','orange','watermelon');

to show in checkbox but if have fruit in table('fruit_select'), in checkbox need to checked. How can i get all data to show with some data in table('fruit_select') to checked?

this my view code to show all data

foreach ($all_fruits as $fruit){
   echo "<label><input type='checkbox' value='".$fruit."'/>".$fruit."</label>"; 
}

Upvotes: 0

Views: 1142

Answers (1)

Jayesh Chitroda
Jayesh Chitroda

Reputation: 5049

You can try this:

$fruit = "apple,orange,banana";
$fruitArr = explode(",",$fruit); // convert selecte fruits to array
foreach ($all_fruits as $fruit){
   $checkedStatus = "";
   // check if $fruit in $selected fruit array - make it checked
   if(in_array($fruit,$fruitArr)) { $checkedStatus ="checked"; }
   echo "<label><input type='checkbox' ".$checkedStatus." value='".$fruit."'/>".$fruit."</label>"; 
}

Output:

<body>
  <label><input type="checkbox" value="apple" checked="">apple</label>
  <label><input type="checkbox" value="banana" checked="">banana</label>
  <label><input type="checkbox" value="kiwi">kiwi</label>
  <label><input type="checkbox" value="melon">melon</label>
  <label><input type="checkbox" value="orange" checked="">orange</label>
  <label><input type="checkbox" value="watermelon">watermelon</label>
</body>


Output:

Upvotes: 3

Related Questions