Reputation: 2226
I have two arrays both having elements in string type. Example :
First Array
$default_complaint = array("Login", "Printer", "Monitor", "Computer",
"Network", "Other");
Second Array
$selected_complaint = explode(" ", $s['kindof_request']);
// Ex : it return like this => array ("Login", "Printer", "Monitor");
Now, how can I create the checkboxes that ticked in html by comparing that two arrays given above. So, I create like this:
<?php
$default_complaint = array("Login", "Printer", "Monitor", "Computer", "Network", "Lain-lain");
$selected_complaint = explode(" ", $s['kindof_request']);
foreach ($default_complaint as $dc) {
foreach ($selected_complaint as $sc) {
$check = strcmp($dc, $sc) ;
if ($check == 0) { //True
echo '<input type="checkbox" checked="checked">'. "$sc" ."<br />";
} else{ //false
echo '<input type="checkbox">'. "$dc"."<br />";
}
}
}
?>
My code still give me weird result. So, How to create like this, => (0) meaning checked.
(0)Login (0)Printer (0)Monitor ()Computer ()Network ()Others
Upvotes: 1
Views: 216
Reputation: 141
You don't need two foreach
loops. Only one will do it. Loop through $default_complaint
array and check whether that element is present in $selected_complaint
array using in_array()
. Try using:
<?php
$default_complaint = array("Login", "Printer", "Monitor", "Computer", "Network", "Other");
$selected_complaint = explode(" ", $s['kindof_request']);
foreach ($default_complaint as $dc)
{
if (in_array($dc, $selected_complaint))
echo '<input type="checkbox" checked>' . $dc . '<br>';
else
echo '<input type="checkbox">' . $dc . '<br>';
}
?>
You can also try array_search()
instead of in_array()
.
Upvotes: 1
Reputation: 1963
You have two loops, but you only want to loop over the first array. The second one is only used for checking.
One possibility for the loop is:
foreach ($default_complaint as $dc) {
if (array_search($dc, $selected_complaint) !== FALSE) {
echo '<input type="checkbox" checked="checked">'. "$dc" ."<br />\n";
} else{
echo '<input type="checkbox">'. "$dc"."<br />\n";
}
}
Upvotes: 1
Reputation: 59701
This should work for you:
(You don't have to do a nested foreach loop)
<?php
$default_complaint = array("Login", "Printer", "Monitor", "Computer", "Network", "Lain-lain");
$selected_complaint = explode(" ", $s['kindof_request']);
foreach($default_complaint as $k => $v) {
if(isset($selected_complaint[$k]) && in_array($selected_complaint[$k], $default_complaint))
echo '<input type="checkbox" checked>' . $v . "<br />";
else
echo '<input type="checkbox">' . $v . "<br />";
}
?>
Upvotes: 2