Reputation: 280
I'm horrible at wording these questions but I hope that gives a good enough idea of what I'm trying to do.
I have 7 pages and 7 images, the images are all "waterfall_01.jpg", "waterfall_02.jpg", etc up to 7.
The code I have is simple so far:
<?php
$cp = basename($_SERVER['PHP_SELF']);
$cf = dirname($_SERVER['PHP_SELF']);
?>
<img src="/img/waterfall_0<?php if ($cp == "about.php" || $cf == "/about"){ echo "1"; }?>.jpg" />
How would I change this code to echo a different number between 1 and 7 based on 7 different pages (some of which have folders with some folders under them represented in a dropdown menu).
Technically I could just write a really long line:
<img src="/img/waterfall_0<?php
if ($cp == "home.php"){ echo "1"; }
if ($cp == "about.php" || $cf == "/about"){ echo "2"; }
if ($cp == "products.php" || $cf == "/products"){ echo "3"; }
if ($cp == "services.php" || $cf == "/services"){ echo "4"; }
if ($cp == "gallery.php" || $cf == "/gallery"){ echo "5"; }
if ($cp == "faq.php"){ echo "6"; }
if ($cp == "contact.php"){ echo "7"; }
?>.jpg" />
I'm not that great with PHP yet, I'm not sure if the above is the best or right way to do this so all help is appreciated!
The test server is http://www.mrobertsdesign.ca/home.php
Thanks in advance!
Upvotes: 0
Views: 98
Reputation: 4216
Both answers by Justin Workman and Satish Sharma are workable solutions. But why not through in the other alternative. Switch statements.
$url = $_SERVER['REQUEST_URI'];
switch ($url) {
case '/about':
case '/about.php':
$img = 2;
break;
case '/contact':
case '/contact.php':
$img = 3;
break;
......
default:
$img = '1';
}
And then output the variable into your img tag.
Upvotes: 4
Reputation: 9635
you need to use if else
<?php
$cp = basename($_SERVER['PHP_SELF']);
$cf = dirname($_SERVER['PHP_SELF']);
if($cp == "home.php")
{
$img_src = "1.jpg";
}
else if($cp == "about.php" || $cf == "/about"))
{
$img_src = "2.jpg";
}
else if($cp == "products.php" || $cf == "/products")
{
$img_src = "3.jpg";
}
else if($cp == "services.php" || $cf == "/services")
{
$img_src = "4.jpg";
}
else if($cp == "gallery.php" || $cf == "/gallery")
{
$img_src = "5.jpg";
}
else if($cp == "faq.php")
{
$img_src = "6.jpg";
}
else if($cp == "contact.php")
{
$img_src = "7.jpg";
}
?>
<img src="/img/waterfall_0<?php echo $img_src;?>" />
Upvotes: 2
Reputation: 388
<?php
$requestedURI = $_SERVER['REQUEST_URI'];
$images = array(
"/home" => "1",
"/about" => "2",
"/products" => "3",
"/services" => "4",
"/gallery" => "5",
"/faq" => "6",
"/contact" => "7",
);
?>
<img src="/img/waterfall_0<?= $images[$requestedURI]; ?>.jpg"/>
Just make sure your URLs match the array keys.
Upvotes: 4