web.curious.gk
web.curious.gk

Reputation: 167

Make dynamic checkbox auto checked if match from another array

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);
    ?>

Upvotes: 1

Views: 5369

Answers (2)

Rahul Sekhar
Rahul Sekhar

Reputation: 2841

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.

Upvotes: 1

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100195

You can do it like:

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

Hope you get it

Upvotes: 2

Related Questions