I'm a front-end developer who is somewhat familiar with but rarely uses PHP. I'm working on a personal project where I'm mostly just using includes to link PHP files together. Here is my overall basic page structure:
<?php include('header.php'); ?>
<?php include('pagetitle.php'); ?>
Page content goes here.
<?php include('footer.php'); ?>
On pagetitle.php, I have an <h1>
,<h2>
and background image relating to which page you're on.
My question is, how do I use conditional statements to put all the page titles/subheadings on pagetitle.php and have them switch depending on what page you're on? So for example, I want
<div id="about">
<h1>About</h1>
<h2>About page subheading</h2>
</div>
to show up on about.php, and
<div id="contact">
<h1>Contact Me</h1>
<h2>Contact page subheading</h2>
</div>
to show up on contact.php, etc. etc. ...but only using pagetitle.php on those pages.
The site isn't huge. It would have no more than 10 pages. Also, I do realize I can just use that page title segment on the respective page, but if possible, I want to try this out.
Thanks!
I would do something like this (not tested, but should work with few, if any, changes.)
(Everyone says that, right? :D):
<?php
/*
create a map that contains the information for each page.
the name of each page maps to an array containing the
(div id, heading 1, & subheading for that page).
*/
$pageinfo = array(
"about.php" => array ("about", "About", "About Page Subheading"),
"contact.php" => array ("contact", "Contact Me", "Contact Page Subheading"),
);
function printinfo($pagename) {
/*
This function will print the info for the current page.
*/
global $pageinfo;
$pagename = basename($pagename);
#make sure we have info for this page
if (!array_key_exists($pagename, $pageinfo) {
echo "<p><b>You did not supply info for page $pagename</b></p>";
return;
}
#we do have info ... continue
$info = $pageinfo[$pagename];
#let's print the div (with its custom id),
echo "<div id='" . $info[0] . "'>\n";
#print the headings
echo "<h1>" . $info[1] . "</h1>\n";
echo "<h2>" . $info[2] . "</h2>\n";
#close the div
echo "</div>\n";
}
?>
Then in each page where you wanted your div, you would place this code:
printinfo($_SERVER['PHP_SELF']);
Other:
This way is more flexible than the other ways, at the sacrifice of no conditional statements. (You specifically requested a solution that had conditional statements; however, in the interest of flexibility & maintainability, this example does not use switch
statements or if
statements.)
Because there are no conditional statements, there is less code to maintain. Granted, you have to setup the array with the information, but if you decided to change the <h2>
to an <h3>
, you would have to make the change at only one location, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With