Reputation: 298
all
I have an array list in which i have cities name and in second array list i have cities name that i wanna show them as checked items.
What i'm trying to do is below
<?php
$mainArr = array("New York", "LA", "London", "Tokyo", "Paris", "Rome");
$checkedArr = array("New York", "Tokyo");
foreach( $mainArr as $main )
{
foreach( $checkedArr as $check ) {
if( $check == $main ) {
echo '<input type="checkbox" name="city" value="$main" checked />', $main;
}else {
echo '<input type="checkbox" name="city" value="$main" />', $main;
}
}
}
?>
But this show duplicate values . How do i get rid of this ? I dont want repeated values.
New york and tokyo should be shown be checked and the rest should be same.
Thanks
Upvotes: -1
Views: 104
Reputation: 37606
Use in_array:
foreach($mainArr as $main) {
if (in_array($main, $checkedArr)) {
echo '<input type="checkbox" name="city" value="$main" checked />', $main;
}
else {
echo '<input type="checkbox" name="city" value="$main" />', $main;
}
}
A bit shorter without code duplication:
foreach($mainArr as $main) {
$checked = in_array($main, $checkArr) ? 'checked' : '' ;
echo '<input type="checkbox" name="city" value="'.$main.'" '.$checked.' /> '.$main;
}
Upvotes: 3