简体   繁体   中英

if else comparing two variables php

I'm current'y having 2 variables, for $arrAns , it contains the different answer that the user select for a checkbox. Example for $arrAns will be 1,2,3. And for $arr , it's the option variable which contains all the options that the question have. Example of $arr will be 1,2,3,4,5,6.

Here's the code whereby I trying to compare, if $arrAns == $arr, then the checkbox input will be "checked". else, it will be leave as blank.

But when I tried using the codes, if user's selection is 1,2,3. It works. But if user selects 2,3,4 non of the options will be "checked". And if user selects 1,3,4 only option 1 will be "checked".

Is there something wrong with the logic in between? In need of help, Thank you!

<?php if ($arrAns[$i] == $arr) { 
 ?>
    <input type="checkbox" name="<?php echo 'qns' . $qID; ?>[]" value="<?php echo $arr; ?>" class="required" checked/> <?php echo $arr; ?><br/>
<?php } else { ?>
    <input type="checkbox" name="<?php echo 'qns' . $qID; ?>[]" value="<?php echo $arr; ?>" class="required"/> <?php echo $arr; ?><br/>
    <?php
} ?>

Instead of seeing if an element exists I think you want to check to see if it is in the array or results.

Change

  <?php if ($arrAns[$i] == $arr) { 

to

  <?php if (in_array($arr, $arrAns)) { 

您可以有效使用in_array()

in_array($arr, $arrAns)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM