0

I trying to compare 2 Arrays and then let the Checkbox to be checked if there are common values between them.

coding

$array_1[]="value1";
$array_1[]="value2";
$array_1[]="value3";
$array_1[]="value4";
$array_1[]="value5";
$array_1[]="value6";
$array_1[]="value7";
$array_1[]="value8";

$array_2[]="value1";
$array_2[]="value3";
$array_2[]="value4";


for($i=0;$i<count($array_1);$i++){
    $checked = isset($array_2[$i])? 'checked' : '';
    echo '<input type="checkbox" ' . $checked .' name="zzz[] "value="'.$array_1[$i].'"> '.$array_1[$i].'<br>';
}

enter image description here

as you can see from the screenshot, the correct result should be right side with value1, value3 and value4. However, my php output is leftside of the screenshot

Anyone knows what's wrong ?

2 Answers 2

1

Since you are working on values, and not on keys, you should use in_array check

for($i=0;$i<count($array_1);$i++){
    $checked = in_array($array_1[$i], $array_2) ? 'checked' : '';
    echo '<input type="checkbox" ' . $checked .' name="zzz[] "value="'.$array_1[$i].'"> '.$array_1[$i].'<br>';
}

Alternatively, you can set the keys to be the same, as Nadir Latif suggests

Sign up to request clarification or add additional context in comments.

Comments

1

The value2 array initialization is wrong. It should be:

$array_2[1]="value1";
$array_2[3]="value3";
$array_2[4]="value4";

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.