This morning while editing our CRON editor that suddenly failed to run, I found an oddity that I can't really explain. Hoping someone here can enlighten me.
Supposing someone can answer this without any context, my question is essentially "Why does 0 == * evaluate to true?"
Details
We store the details of all active CRON jobs in a MySQL table. The type for fields Minutes, Hours, Days and Months is varchar
with default '*'. When editing a CRON job, we have a select that should should have selected the current value from a fetched row, labeled below as $CRON
and an example of which follows.
Array ( [CRONID] => 10 [Minutes] => 21 [Hours] => 6 [Days] => * [Months] => * [Weekday] => * [File] => CRON_Prop_44.php [Status] => 1 [CreateBy] => 128 [CreateDate] => 2014-02-20 [ChangeBy] => 128 [ChangeDate] => 2014-02-20 )
The Broken Select
The following would produce a select with Sunday as the selected option. Inspector reveals that both option value="*" and option value="0" are selected.
<select name="Weekday">
<option value="*" <?php if ($CRON['Weekday'] == "*" ) { echo "selected";} ?> >* - Every day</option>
<?php
$x = 0;
while ($x < 7) {
switch ($x) {
case 0:
$dayname = "Sunday";
break;
case 1:
$dayname = "Monday";
break;
case 2:
$dayname = "Tuesday";
break;
case 3:
$dayname = "Wednesday";
break;
case 4:
$dayname = "Thursday";
break;
case 5:
$dayname = "Friday";
break;
case 6:
$dayname = "Saturday";
break;
}
?>
<option value="<?php echo $x; ?><?php if ($CRON['Weekday'] == $x ) { echo "selected";} ?> ><?php echo $dayname; ?></option>
<?php
$x++;
}?>
The fact that Sunday is also selected leads me to believe that 0 == *
is true. I can get the above working as expected by adding the ===
comparison operator instead of ==
, but I don't understand why. Is it something with the switch? The option value="0"? Or, as the title suggests, that 0 == *
is true?
The (Sort of) Functioning Select
I thought the previous person's code above was a bit messy, so I'm currently doing the following. Still, changing the ===
to ==
results in only Sunday being selected.
<select name="Weekday">
<option value="*" <?php if ($CRON['Weekday'] == "*" ) { echo "selected";} ?> >* - Every day</option>
<?php
$days = array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
$x = 0;
while ($x < 7) {
echo '<option value="' . $x . '" ' . (($CRON['Weekday'] == $x) ? 'selected' : "") . '>' . $days[$x] . '</option>';
$x++;
}
?>
</select>
If you've lasted to the end of this post, please tell me what I am missing?