Hi all, I have this piece of code that prints a word/title for each page. Its alot longer than this <? if(preg_match("/aboutus\.html/",$_SERVER['REQUEST_URI'])) { print 'About us & contact'; } if(preg_match("/beaches\.html/",$_SERVER['REQUEST_URI'])) { print 'All Beaches'; } if(preg_match("/cafes\.html/",$_SERVER['REQUEST_URI'])) { print 'Cafes & Bars'; } if(preg_match("/hotels\.html/",$_SERVER['REQUEST_URI'])) { print 'Accommodation'; } else { print 'Home'; } ?> PHP: Is there better or faster or easier way to do this ? You can see I am no expert with this
why not make use of arrays? $array = array('aboutus' => 'About us', 'beaches' => 'Beaches'); foreach ($array AS $page=>$title) { if (substr($_SERVER['REQUEST_URI'], 0, strlen($page) == $page) { echo $title . ' found'; } } Code (markup): something like this, but the rest you may figure out..
$titles = [ 'aboutus' => 'About Us', 'beaches' => 'Beaches', // ... ]; $file = basename($_SERVER['REQUEST_URI'], '.html'); if (isset($titles[$file])) { echo $titles[$file]; } else { echo 'Home'; } PHP:
This worked.. $titles = array( 'aboutus' => 'About Us', 'beaches' => 'Beaches', // ... ); $file = basename($_SERVER['REQUEST_URI'], '.html'); if (isset($titles[$file])) { echo $titles[$file]; } else { echo 'Home'; } PHP: Thanks alot..
One last question though.. If I wanted to make multiple selections say /guide/ /guide/aboutus.html to Guide > About us $titles = array( 'aboutus' => 'About Us', 'guide' => 'Guide', 'beaches' => 'Beaches', 'cafes' => 'Cafes', 'my-cafe' => 'My Cafe', // ... ); $file = basename($_SERVER['REQUEST_URI'], '.html'); if (isset($titles[$file])) { echo $titles[$file]; } else { echo 'Home'; } PHP: Guide > About us Cafes Cafes > My Cafe is it possible ?