这个php语句有什么问题

时间:2013-11-26 16:36:39

标签: php

我似乎无法弄清楚如何编写以下内容。下面的语句在一个php字符串中回显,无论$ sex的实际价值是什么,它总是显示F为检查值?

我找到了解决方案,并在下面发布了工作代码!

 $string = "Sex  :  
           <input type='radio' name='sex' value='m' checked='<?php if($sex == \"m\"){ echo \"checked\"; }else{echo \"\"; } ?>' /> Male
           &nbsp;&nbsp;
           <input type='radio' name='sex' value='f' checked='<?php if($sex == \"f\"){ echo \"checked\"; }else{echo \"\"; } ?>' /> Female<br /><br />";

下面的工作代码:(注意不要破坏“已检查”语句并在if语句中使用单引号 - 有效吗?)

  $the_result = $the_result."Gender  :  <input type='radio' name='sex' value='m'";
  if ($sex == 'm') {
    $the_result = $the_result." checked='checked'";
  }
  $the_result = $the_result."/> Male  ";
  $the_result = $the_result."<input type='radio' name='sex' value='f'";
  if ($sex == "f") {
    $the_result = $the_result." checked='checked'";
  }

  $the_result = $the_result."/> Female ";

1 个答案:

答案 0 :(得分:2)

另一种,也许更容易理解的方式来写这个:

<?php
  $str = "Sex  :  <input type='radio' name='sex' value='m' checked='";
  if ($sex == "m") {
    $str = $str."checked";
  } else {
    $str = $str."'";
  }
  $str = $str."/> Male  ";
  $str = $str."<input type='radio' name='sex' value='f' checked='";
  if ($sex == "f") {
    $str = $str."checked";
  } else {
    $str = $str."'";
  }
  $str = $str."/> Female ";
  $str = "<br/><br/>";
  echo $str;

因为你有很多应该被回应的逻辑,你应该构造你的整个字符串,然后回应它,而不是试图把逻辑内联。这样您就可以验证字符串是否正确且更容易查看您正在做什么。

请注意,虽然上面是重构您的确切逻辑,但字符串构造可以通过多种方式完成:

<?php
  $str = "Sex  :  ";
  if ($sex == "m") {
    $str = $str."<input type='radio' name='sex' value='m' checked='checked'/> Male";
    $str = $str."<input type='radio' name='sex' value='f' checked=''/> Female";
  } else if ($sex == "f") {
    $str = $str."<input type='radio' name='sex' value='m' checked=''/> Male";
    $str = $str."<input type='radio' name='sex' value='f' checked='checked'/> Female";
  } //Note if not m or f nothing is displayed
  $str = $str."<br/><br/>";
  echo $str;

或者:

<?php
  $maleChecked = "";
  $femaleChecked = "";
  if ($sex == "m") { $maleChecked = "checked"; }
  if ($sex == "f") { $femaleChecked = "checked"; }
?>
<input type='radio' name='sex' value='m' checked='<?php echo $maleChecked?>'/> Male
<input type='radio' name='sex' value='f' checked='<?php echo $femaleChecked?>'/> Female