php
  • syntax
  • 2012-12-03 35 views -3 likes 
    -3

    那麼,這個工程:PHP語法的使用和:

    <?php 
    $value = ($_POST['x']) ? $_POST['x'] : $y[0]; 
    $output = '<input type="text" name="field1" value="'.$value.'">'; 
    ?> 
    

    但是,如何讓它在這種情況下工作:

    <?php 
        $output = '<input type="text" name="field1" value="'.$($_POST['x']) ? $_POST['x'] : $y[0];.'">'; 
    ?> 
    
    +6

    減少代碼的行數的程序可以是美德的感覺,在這種情況下,它是相反的。您正在降低代碼的可讀性(從而降低可維護性)。 – Quentin

    回答

    4

    只是刪除了第一筆錢,不屬於那裏,它包裝成括號並刪除分號:

    $output = '<input type="text" name="field1" value="'.(($_POST['x']) ? $_POST['x'] : $y[0]).'">'; 
    
    +0

    謝謝!這第一美元是一個錯字。但增加額外的括號 - 從來沒有想過這個。 – AnuVi

    1

    別無分號:

    value="' . ($_POST['x'] ? $_POST['x'] : $y[0]) .'">'; 
    

    我也得到你想要使用isset($_POST['x'])

    0
    <input type="type" value="<?php echo $condition ? $variant1 : $variant2 ?>" /> 
    
    +1

    請考慮添加評論到您的「僅限代碼」答案。 – cem

    +0

    「Talk is cheap,給我看代碼。」 - Linus Torvalds。代碼的一行中不清楚什麼? –

    +0

    具體說來:他沒有得到三元運算符的想法,所以給他另一個代碼的例子只是一個元回答,並沒有幫助他解決他的問題。由於你是新手入門(或者這是你的第一個貢獻),請查看meta上的這個非常有用的答案(特別是第10號):http://meta.stackexchange.com/questions/118582/what-is-an -acceptable回答 – cem

    相關問題