I'm working on a PHP-written html calendar that writes each day of the month inside a while loop.
Each day of the month is inside a pair of tags and certain days need a title attribute in the tag. Those days will be obtained from the MySQL db and stored in an array like this: $array($day_number=>$quantity).
An example array might be: (3=>5, 12=>4, 15=>6, 22=>10, 27=>2, 31=>4). The array would only contain keys for days where the quantity is not zero.
I can think of two ways to do this. I'm wondering which one is more efficient, or if there is another, best way.
Option 1.) Check the array at each iteration of the html-creating loop to see if it contains the corresponding day. If so, add the appropriate title attribute to the tag. So I would be using something like:
$day = 1;
while($day < 31) {
if(array_key_exists($day,$array)) {
echo "<td title=\"$array['$day'] spots available\">$day</td>";
}
else echo "<td title\"No spots available for this date\">$day</td>";
$day++;
}
2.) Use loop to put entire calendar into a string variable, then use string functions to insert special title attributes.
$day = 1;
while($day < 31) {
$month .= "<td>$day</td>";
$day++;
}
foreach($array as $day_number=>$quantity) {
$month = str_replace("<td>$day_number</td>","<td title=\"$quantity spots available\">$day_number</td>",$month)
}
In this application, either method will be done very quickly but my question is more general. Is it better to use string functions after the loop that creates the basic html, or to checking/processing at each iteration? Or is there a third, best way?
I have learned PHP entirely by myself using internet resources so I have no idea how bad my coding may be. Any help is appreciated.
Thank you.