-1

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

1

1 Answer 1

3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.