0

Can someone help me to solve this issue?

Below code i used in an edit page, and i want to compare the checkbox values and if it is matching make it as checked.

Example of my two array values

$CategoryDetails : Array ( [0] => 6 [1] => 1 )
$Category_data : Array ( [0] => 1 [1] => 3 [2] => 6 [3] => 2 [4] => 4 [5] => 7)

$Category_data is am using to create checkbox and $CategoryDetails is the selected values. So as per above eg checkbox 1 & 3 should be checked, but below code giving me only one checked ie. checkbox3

I need to compare each value of array1 with array2.

<?php
    $CategoryDetails = isset($category_list) ? $category_list : ' ';
    $Category = dbSelectByWhere("Highlight_categories", "WHERE Highlight_cat_status=1", "Order By Highlight_Category_name");
    $k = 0;
    while ($Category_data = dbFetchArray($Category)) {
        ?>
        <input type="checkbox" name="category[]" id="Category" value="<?php echo $Category_data['Highlight_category_id']; ?>" data-parsley-mincheck="1" required class="flat" <?php
        if (isset($CategoryDetails) && ($CategoryDetails[$k] == $Category_data['Highlight_category_id'])) {
            echo 'checked';
            if ($k < (count($CategoryDetails) - 1)) {
                $k++;
            }
        }
        ?>/> <?php echo $Category_data['Highlight_Category_name']; ?>
    <?php } ?>

1 Answer 1

2

1st : You need to use in_array function.

2nd : in_array function searches an array for a specific value .if value exists it will return true else it will return false .

3rd : If empty declare the variable as array

$CategoryDetails = isset($category_list) ? $category_list : array();

PHP :

while ($Category_data = dbFetchArray($Category)) {
        ?>
        <input type="checkbox" name="category[]" id="Category" value="<?php echo $Category_data['Highlight_category_id']; ?>" data-parsley-mincheck="1" required class="flat" <?php
        if (isset($CategoryDetails) && in_array($Category_data['Highlight_category_id'],$CategoryDetails)) {
            echo 'checked';
        }
        ?>/> <?php echo $Category_data['Highlight_Category_name']; ?>
        <?php } ?>
Sign up to request clarification or add additional context in comments.

1 Comment

Think it should be $CategoryDetails = isset($category_list) ? $category_list : array();

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.