Jess McKenzie
Jess McKenzie

Reputation: 8385

if statement is equal to a value

I have a result(string) of 1,1,0,0 - These come from $sub_array['state']

Currently all of my check boxes are checked. How can I code the code below so that if its 1 its checked else its not? as the current code gives them all 'checked'

<?php

    foreach($assoc_categories as $sub_array)
    {
        if($sub_array['state'] == 1)
        {
            $checked_state = " checked='checked'";
        }                  
?>
<div>
    <input 
        class="checkbox" 
        type="checkbox" 
        name="product_category" 
        class="product_category_selector" 
        id="product_category_<?php echo $sub_array['cat_id']; ?>" 
        data-id="<?php echo $sub_array['cat_id']; ?>" 
        <?php echo $checked_state; ?> 
    /> 
    <?php echo $sub_array['name']; ?>
</div>
<input 
    class="order" 
    type="input" 
    value="<?php echo $sub_array['sorder']; ?>" 
/>
<?php
    }
?>

Upvotes: 0

Views: 148

Answers (2)

sensorario
sensorario

Reputation: 21698

You forget to reset checked_state or reset it to '' if $sub_array['state'] is equal to 0.

<?php

    $assoc_categories = array(
        array('state'=>1, 'cat_id'=>1, 'name'=>'one',   'sorder'=>1),
        array('state'=>1, 'cat_id'=>2, 'name'=>'three', 'sorder'=>2),
        array('state'=>0, 'cat_id'=>3, 'name'=>'four',  'sorder'=>3),
        array('state'=>0, 'cat_id'=>4, 'name'=>'five',  'sorder'=>4),
    );

    foreach($assoc_categories as $sub_array)
    {
        $checked_state = $sub_array['state'] == 1 ? " checked='checked'" : '';
?>
<div>
    <input
        class="checkbox"
        type="checkbox"
        name="product_category"
        class="product_category_selector"
        id="product_category_<?php echo $sub_array['cat_id']; ?>"
        data-id="<?php echo $sub_array['cat_id']; ?>"
        <?php echo $checked_state; ?>
    />
    <?php echo $sub_array['name']; ?>
</div>
<input
    class="order"
    type="input"
    value="<?php echo $sub_array['sorder']; ?>"
/>
<?php
    }

Upvotes: 0

Tigger
Tigger

Reputation: 9130

Change:

if($sub_array['state'] == 1)
{
    $checked_state = " checked='checked'";
}

To:

if($sub_array['state'] == 1)
{
    $checked_state = " checked='checked'";
} else 
{
    $checked_state = "";
}

Basically, you are not clearing the previous value as the loop continues.

Alternatively, you could use:

$checked_state = ($sub_array['state'] == 1) ? " checked='checked'" : "" ;

Upvotes: 1

Related Questions