I am trying to change a div's background image based on the day of the week. The images are in a folder named 'img' I have the following code;
html
<?php
$images_by_day = array('monday.jpg', 'tuesday.jpg', 'wednesday.jpg', ...);
$image_for_today = $images_by_day[date('w')];
?>
<div class="jumbotron indx-BG">
//content
</div>
css (external style sheet)
.indx-BG {
background: url('../img/<?php echo $image_for_today ?>.jpg') no-repeat center center;
}
Its better you define seven different classes with different background images within the css file and then apply those classes within the elements using php file.
Like:
<div class="container <?php echo date('l')?>-bg" id="indx-jumbo">
//content
</div>
And in your css file you define css classes like:
.monday-bg {
background: url('../img/image_for_monday.jpg') no-repeat center center;
}
.tuesday-bg {
background: url('../img/image_for_tuesday.jpg') no-repeat center center;
}
.
.
.
.sunday-bg {
background: url('../img/image_for_sunday.jpg') no-repeat center center;
}
You shouldn't use PHP in a CSS file. A way to solve this problem is by adding the background-image inline, something like this:
<div class="container" id="indx-jumbo" style="background-image: url('../img/<?php echo $image_for_today ?>.jpg')">
//content
</div>
You can't use PHP in css file. You can add background image
inline. Please check following code.
<div class="container" id="indx-jumbo" style="background-image: url('../img/<?php echo date( "l", $timestamp); ?>.jpg')">
//content
</div>
<?php
$images_by_day = array('sunday.jpg','monday.jpg', 'tuesday.jpg',
'wednesday.jpg','thursday.jpg','friday.jpg','saturday.jpg');
$image_for_today = $images_by_day[date('w')];
?>
<div class="container" id="indx-jumbo"
style=" background: url('../img/<?php echo $image_for_today ?>') no-repeat center center;">
//Content
</div>
Try to this.
<?php
$images_by_day = array('monday.jpg', 'tuesday.jpg', 'wednesday.jpg', 'thursday.jpg','friday.jpg','saturday.jpg','sunday.jpg');
$today = date('l');
foreach ($images_by_day as $key => $value) {
$day = substr($value,0,-4);
$str = strcasecmp($day, $today);
if($str == '0'){
$background = $value;
}
}
?>
<div class="container" id="indx-jumbo" style="background-image: url('../img/<?= $background; ?>');">
//content
</div>
You need to check if your image name contains day of a week. You can do it easily with php's substring inbuilt functions.
<?php
foreach($imagArray as $image)
{
if(strpos($image,date('l'))
{
//display image and exit
}
}
?>