简体   繁体   中英

Changing a variable's value based on another variable in PHP

first let me say I am trying very hard to learn PHP, and the more I learn, the more I want to learn and use the language. I'm primarily an HTML5/CSS3 coder, and am trying to make my sites more efficient by using PHP.

Here is my current dilemma. I am attempting to utilize variables to change values as required. At the beginning of each page file I have declared the page name, called my functions file and called head and header functions:

<?php
    $page = 'contact';
    include('functions.php');
    head();
    header();
?>

A slight variation of this is included in all page files. Things are good.

Now, in my functions.php I have a variable for the meta title value, ie $title , and have declared it as a global.

How do I change the value of this variable based on the value of the $page variable? Here is what I have added to the functions.php file, but I am quite sure it is incorrect, as it is not working:

$title = array {
    if ($page == 'contact') {
        echo 'Contact Us';
    }
}

I'm not just looking for the right code, but an explanation if possible. Thanks in advance for your assistance.

You can store all titles in an associative array:

$TITLES = array(
    'contact' => 'Contact Us',
    'home' => 'Welcome',
);

$title = "Some Default Title"; 

if(isset($TITLES[$page])){ //check to see if we have a specific title set up 

    $title = $TITLES[$page]; //override it if it is set 

} 

You can simply create an associative array that contains pages as keys and titles as values, then you can get the value such as:

$titles = array('Home' => 'Welcome to Home', 'contact' => 'Contact Us');

if(array_key_exists($page, $titles)){
 echo $titkes[$page];
}

You can use a function with an argument and then use switch cases to check the variable value and return the appropriate text.

function pageTitle($var) {
    switch ($var)
    {
    case "contact":
      return "Contact Us";
      break;
    case "about":
      return "About Us";
      break;
    .
    .
    .
    default:
      return "Default"; //default case
    }
}

And use it like so:

<?php
    $page = 'contact';
    include('functions.php');
    head();

    echo PageTitle('contact'); //should echo 'Contact Us'
    header();

?>

What I'd recommend is perhaps a switch case statement to store all of the possible types.

switch($page){
    case "contact":
        $title = "Contact Us";
        break;
    case "about":
        $title = "About Us";
        break;
    default:
        $title = "Default Title";
        break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM