1

I have this string:

$hours = '7, 8, 12';
$hourData = explode(', ', $hours);

if I var_dump($hourData), it returns:

array(3) {
    [0]=>
    string(1) "7"
    [1]=>
    string(2) "8"
    [2]=>
    string(2) "12"
}

and I have this code:

<?php for ($i=0; $i <= 23 ; $i++) { ?>
    <div class="fl">
        <input type="checkbox" name="limit_hour[]" value="<?php echo $i ?>" class="fl limit_hour"
        <!-- ======================================================================== -->
        <?php echo (isset($hourData[$i]) && $i == $hourData[$i] ? 'checked' : '') ?>>
        <!-- ======================================================================== -->
        <span class="fl lmBox"><?php echo $i ?>:00 - <?php echo $i ?>:59</span>
    </div>  
<?php } ?>

this code:

<?php echo (isset($hourData[$i]) && $i == $hourData[$i] ? 'checked' : '') ?>

I want to echo 'checked' for the checkbox who got the same value as my $hourData array value.

What should I do?

1
  • 1
    I asume $i is the hour. 'in_array($i, $hourData)' would return a true/false. Commented Oct 28, 2014 at 7:54

4 Answers 4

6

Just follow up the ternary and use in_array()

<?php echo (in_array($i, $hourData) ? 'checked' : ''); ?>

Much like this:

<input 
    type="checkbox" 
    name="limit_hour[]" 
    value="<?php echo $i; ?>" 
    class="fl limit_hour"
    <?php echo (in_array($i, $hourData) ? 'checked' : ''); ?> 
/>

Using $hourData[$i] wouldn't make sense since they will never match.

First Iteration:

$i = 0
(isset($hourData[$i]) && $i == $hourData[$i]
   ^ $hourData[$i]   AND  0 == $hourData[$i] // 7
      this does exist
Sign up to request clarification or add additional context in comments.

1 Comment

yes this solved my problem :D, I never thought it would be this simple, thank you sir :D
1

I am assuming you actually want the value not index. I.e. check if $i exists as value in $hourData array.

<?php
echo in_array($i, $hourData) ? 'checked' : ''
?>

Comments

1
<?php for ($i=0; $i <= 23 ; $i++) { 
 if(in_array($i, $hourData){
     $checked = "checked";
 }else{
     $checked = "";
 }
?>
    <div class="fl">
        <input type="checkbox" name="limit_hour[]" value="<?php echo $i ?>" class="fl limit_hour" <?php echo $checked; ?>>
        <!-- ======================================================================== -->
        <span class="fl lmBox"><?php echo $i ?>:00 - <?php echo $i ?>:59</span>
    </div>  
<?php } ?>

this will set the checked value if there is else it leaves it empty, so it works fine.

As I stated in a comment: "I asume $i is the hour. 'in_array($i, $hourData)' would return a true/false."

Comments

0

Seems to me that comparing if a value is contained in an array is sufficient:

 <?php echo (in_array($i, $hourData)) ? 'checked="checked"' : ''); ?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.