How to set page title with php conditional

Viewed 309

Im trying to see different title for different page

In header.php i check file name to set correct title like this

<?php
$page = basename($_SERVER['PHP_SELF']);

if ($page == 'index.php'): ?>
<title>Home page</title>
<?php elseif($page == 'price.php'): ?>
 <title>Price page</title>
<?php elseif($page == 'areas.php'): ?>
  <title>Areas page</title>
<?php endif; ?>

Only for <?php elseif($page == 'price.php'): ?> is not working i mean it is not printing the title tag for some reason , file name price.php is correct . If i print echo $page in <?php elseif($page == 'price.php'): ?> it is showing me price.php

What is the problem ?

2 Answers

With match expression introduced in php 8 more effective and elegant way than conditions if-elseif... I hope this simplify your code and solve the problem.

<?php
$page = match(basename($_SERVER['PHP_SELF'])) {
    'index.php' => 'Home page',
    'price.php' => 'Price page',
    'areas.php' => 'Areas page',
    default => 'Unknown page'
};
?>
<title><?=$page?></title>

As an alternative syntax, you may use:

<?php

$title = '';

switch (basename($_SERVER['PHP_SELF'])) {

  case ('index.php') : $title = 'Home page'; break;
  case ('price.php') : $title = 'Price page'; break;
  case ('areas.php') : $title = 'Areas page'; break;
}

echo '<title>'.$title.'</title>';

?>
Related