1

Here's my php script, it pulls record from DB then it creates dynamic checkbox and the checkbox is a list of fruits that user needs to tick for selection.

What I want to achieve is to make the checkbox checked automatically if it matches some info from another array.

let say array contents are Banana, Mango, Apple. I want those checkbox to have checked automatically. how can i do that? thanks.

   <?php
    fruits = $stmt->prepare("SELECT * FROM fruits ORDER by fruit_id ASC");
    $fruits->execute();

    $cols = 6;

    do {
    echo "<tr>";
    for ($i = 1; $i <= $cols; $i++) {

    $row = $fruits->fetch(PDO::FETCH_ASSOC);

    if ($row) {
    $fruit_id = $row['fruit_id'];
    $fruit_name = $row['fruit_name'];
    ?>

    <td>
    <table>
    <tr valign="top">
    <td>
    <?php echo '<input type="checkbox" id="fruit_id[]" name="fruit_id[]" value="' . $fruit_id . '"/>' . $fruit_name . "\n"; ?>
    </td>
    <td width="30">&nbsp;</td>
    </tr>
    </table>
    </td>
    <?php
    } else {
    echo "<td>&nbsp;</td>";
    }
    }
    } while ($row);
    ?>
0

2 Answers 2

2

You can do it like:

if(in_array("apple", $yourArray)) { echo "checked"; }

Hope you get it

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

Comments

1

Let's say your array of autochecked fruit is $autocheck_array. Then you can use:

<?php echo '<input type="checkbox" id="fruit_id[]" name="fruit_id[]" value="' 
. $fruit_id . '"' . (in_array($fruit_name, $autocheck_array) ? ' checked="checked"' : '') 
. '"/>' . $fruit_name . "\n"; ?>

You can easily change the ternary operator to an if statement, if you prefer it that way, but I prefer the single lined approach.

3 Comments

Tried this but it doesn't populate the check. $autocheck_array = array("apple", "banana"); <?php echo '<input type="checkbox" id="fruit_id[]" name="fruit_id[]" value="' . $fruit_id . (in_array($fruit_name, $autocheck_array) ? ' checked="checked"' : '') . '"/>' . $fruit_name . "\n"; ?>
Missed a quote after value="' . $fruit_id . - edited, try with the current code. The simplest way to debug this is to see what HTML output it's giving. Just view the source of the resulting page.
By the way, why do you have the id set to fruit_id[]? You only require this of the name. The id won't be available to php once the query is sent, and should be unique within your HTML.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.