如何比较变量中的值与字符串

时间:2014-02-11 23:00:31

标签: php html forms

我有以下代码,但它似乎无法正常工作

html:

    <input class="radio_1" type="radio" name="radio_group_1" value="Male">
    <label for class="gender_male" ="radio_1">Male</label>  

    <input class="radio_2" type="radio" name="radio_group_1" value="Female"> 
    <label for class="gender_female" ="radio_2">Female</label>

php:

  $gender=mysqli_escape_string($db,$_POST['radio_group_1']);//gender

以下代码似乎无法正常工作

 if($gender=="male")
{
$profile_photo = "profile_photo_encrypt/male.jpg";
}
if($gender=="female")
{
$profile_photo = "profile_photo_encrypt/female.jpg";
 } 

2 个答案:

答案 0 :(得分:1)

使用此.. 区分大小写是问题

    if($gender=="Male")
{
$profile_photo = "profile_photo_encrypt/male.jpg";
}
if($gender=="Female")
{
$profile_photo = "profile_photo_encrypt/female.jpg";
 } 

答案 1 :(得分:0)

如上所述,区分大小写是这里的问题。

为避免区分大小写的问题,您可以使用strcmp。使用此函数将比较2个字符串,如果匹配则返回0.

if(strcmp($gender, "Male") == 0)
{
    $profile_photo = "profile_photo_encrypt/male.jpg";
}

if(strcmp($gender, "Female") == 0)
{
    $profile_photo = "profile_photo_encrypt/female.jpg";
}

您还可以考虑使用switch语句,并使用strtolower

将文字设为小写
switch(strtolower($gender))
{
    case "male": $profile_photo = "profile_photo_encrypt/male.jpg"; break;
    case "female": $profile_photo = "profile_photo_encrypt/female.jpg"; break;
}