PHP if/else statement

前端 未结 6 362
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-20 23:29

I\'m a complete newbie to PHP but found it can be very useful. How can I write the following statement in PHP:

If body ID = \"home\" then insert some html, e.g.

相关标签:
6条回答
  • 2021-01-20 23:54

    You can try using this :

    $html = '';
    if ( $body_id === 'home' )
    {
        $html .= '<h1>I am home!</h1>';
    }
    else
    {
        $html .= '<p>I\'m not home.</p>';
    }
    
    echo $html;
    

    This will echo the html code depending on the $body_id variable and what it contains.

    0 讨论(0)
  • 2021-01-20 23:54

    You can use a switch command like so:

    switch($body)
    {
        case 'home': //$body == 'home' ?
            echo '<h1>I am home!</h1>';
        break;
    
        case 'not_home':
        default:
            echo '<p>I'm not home.</p>';
        break;
    }
    

    The default means that if $body does not match any case values, then that will be used, the default is optional.

    Another way is as you say, if/else statements, but if within template / view pages you should try and use like so:

    <?php if ($body == 'home'):?>
        <h1>I am home!</h1>
    <?php else:?>
        <p>I'm not home!</p>
    <?php endif; ?>
    
    0 讨论(0)
  • 2021-01-21 00:02

    Doing it with native PHP templating:

    <?php if ($bodyID==='home') { ?>
        <h1>I am home!</h1>
    <?php } else { ?>
        <p>I'm not home!</p>
    <?php } ?>
    
    0 讨论(0)
  • 2021-01-21 00:09

    Assuming $bodyID is a variable:

    <?php 
        if ($bodyID==='home') {
            echo "<h1>I am home!</h1>";}
        else {
            echo "<p>I'm not home!</p>";}
    ?>
    
    0 讨论(0)
  • 2021-01-21 00:14

    you can try in the following way:

    $body_id = "home";
    
    if ($body_id == "home") {
        echo "I am home!";
    } else {
        echo "I am not home!";
    }
    

    or

    $body_id = "home"; 
    
    if (strcmp($body_id, "home") !== 0) { 
        echo 'I am not home!'; 
    } 
    else { 
        echo 'I am home!'; 
    } 
    

    Reference:

    https://www.geeksforgeeks.org/string-comparison-using-vs-strcmp-in-php/
    
    0 讨论(0)
  • 2021-01-21 00:18

    Personally I think that the best way to do that without refreshing and without having to set a variable (like $body or something like that) is to use a javascript code, this because "communications" between JS & PHP is a one-way communication.

    <script language="javascript">
    <!--
    if( document.body.id === "home" ){
        window.document.write("<h1>I am home!</h1>") ;
    }
    else{
        window.document.write("<p>I'm not home!</p>") ;
    }
    -->
    </script>
    

    otherwise you can build a form and then take the body.id value using $_GET function... It always depends on what you've to do after you now body.id value.

    Hope this will be usefull & clear.

    0 讨论(0)
提交回复
热议问题