-2
<?php
$date = '2017-08-22';
$year = substr($date, 0, 4);
$month = substr($date, 5, 2);
$day = substr($date, 8, 2);
?>

<select>
<?php
for ($i=1; $i < 30; $i++) { ?>
<option value="<?php echo $i; ?>" <?php if($day === $i){ echo "selected"; }; ?>><?php echo $i; ?></option>
<?php } ?>

</select>

the code is not executing because substr is not running before the for loop. the select should be selected on day 22 but it is not selecting anything. if i change $day = 22;, it works. how can i fix this with the substring?

baileyJchoi
  • 473
  • 5
  • 17

5 Answers5

2

you're doing === which is a strict match, since your year/month/day are all strings your day will never work. you need to use ==

'22' === 22; // false
'22' == 22; // true
Jonathan
  • 2,778
  • 13
  • 23
1

Try this

You just change the below line in <option> tag inside.

if($day === $i)

to

if($day == $i)
0

Try to var_dump $day after the substr see what happens. Namely, you're using === the triple equals comparison which will also check type. substr returns a string and you're comparing it to an integer, so the condition is never true.

jake2389
  • 1,166
  • 8
  • 22
0

Yes I commented some issue you can use below code to fix

<?php
    $date = '2017-08-22';
    $dateSec = strtotime($date);
    $year = date("Y",$dateSec);
    $month = date("m",$dateSec);
    $day = date("d",$dateSec);
    $day_in_month = date("t",$dateSec);
    echo "<select>";
    for ($i=1; $i <= $day_in_month; $i++) {
            $selected = ($day==$i) ? ' selected ':'';
            echo "<option $selected value='$i'>$i</option>";
    }
    echo "</select>";
?>
Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109
0

The problem comes when you compare the values through === because the values you are comparing does not contain the same data type. $day contain the 'string' data type & the '$i' contain the 'int' data type.

So, for resolving the issue, there are two possible solutions which are as follows, try any one:

Either you use == instead of ===, just like this:

if($day == $i)

OR

Use (int) data type when assigning values to $day, $month & $year variable, just like this:

$day = (int)substr($date, 8, 2);

Hope, this may be helpful to you.

Prateek Verma
  • 869
  • 1
  • 6
  • 9