Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/245.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP if语句数字作为字符串_Php_If Statement - Fatal编程技术网

PHP if语句数字作为字符串

PHP if语句数字作为字符串,php,if-statement,Php,If Statement,$InboundTextBody=“1”。当代码运行时,它不会设置$TypeOptions=good,但是如果我像$InboundTextBody=“one”那样拼写单词one,那么我会得到很棒的。如何让if语句将输入1识别为字符串 if ($InboundTextBody === "1") { $TypeOptions = "good"; } elseif ($InboundTextBody === "One") { $TypeOptions = "great"; } else

$InboundTextBody=“1”
。当代码运行时,它不会设置
$TypeOptions=good
,但是如果我像
$InboundTextBody=“one”
那样拼写单词one,那么我会得到
很棒的
。如何让if语句将输入
1
识别为字符串

if ($InboundTextBody === "1") {
    $TypeOptions = "good";
}
elseif ($InboundTextBody === "One") {
    $TypeOptions = "great";
}
elseif ($InboundTextBody === "3") {
    $TypeOptions = "best";
}

您可以使用强制转换操作符来执行此操作

将该代码置于条件之前:

$InboundTextBody = (string)$InboundTextBody;
然后:


将返回所需内容。

当您使用
=
时,PHP将把
“1”
作为字符串进行评估。如果
$InboundTextBody
等于
1
(数字),则它将无法正常工作。您可以尝试使用
=
而不是
==
使其工作(因为
==
是严格的比较运算符,而
=
不是)。 以下是它的工作原理:

if ($InboundTextBody == "1"){
    $TypeOptions = "good";
}
elseif ($InboundTextBody == "One"){
    $TypeOptions = "great";
}
elseif ($InboundTextBody == "3"){
    $TypeOptions = "best";
}
或者,如果您确定每个可能的
$InboundTextBody
都应该是字符串,那么您应该在
if
语句之前再添加一行:

$InboundTextBody = strval($InboundTextBody);
if ($InboundTextBody === "1"){
    $TypeOptions = "good";
}
elseif ($InboundTextBody === "One"){
    $TypeOptions = "great";
}
elseif ($InboundTextBody === "3"){
    $TypeOptions = "best";
}

除了驼峰式的大小写之外,您的代码没有任何问题

您的输入已经是一个字符串。将数字用引号括起来,以便将其解析为字符串。您可以使用检查。
1
,因为变量类型字符串仍然是单个字符
1
,而不是
1
。您可以创建一个包含所有变体的数组,然后在数组中使用
$InboundTextBody=“1”;如果($InboundTextBody==“1”){echo“HERE\n”}
输出“HERE”。因此,您共享的代码工作正常(
$InboundTextBody=“1”
位于顶部,然后是较大的代码块)。请分享您正在运行的复制问题的实际代码。如果他们得到了
很棒的
(这是我如何理解问题的)那么
$InboundTextBody
必须是
一个
。我们无法知道
$InboundTextBody
是什么以及在哪里,您已经知道了。问题的一开始:
$InboundTextBody=“1”
@smarx如果它实际上是
$InboundTextBody=“1”
,那么它可以正常工作。同意。(我对这个问题也做了很多评论。)那么我们为什么不等着看实际的代码是什么呢?这正是问题的开始:
$InboundTextBody=“1”
$InboundTextBody = strval($InboundTextBody);
if ($InboundTextBody === "1"){
    $TypeOptions = "good";
}
elseif ($InboundTextBody === "One"){
    $TypeOptions = "great";
}
elseif ($InboundTextBody === "3"){
    $TypeOptions = "best";
}
<?php

$InboundTextBody = "1";

if ($InboundTextBody === "1"){
    $TypeOptions = "good";
}
elseif ($InboundTextBody === "One"){
    $TypeOptions = "great";
}
elseif ($InboundTextBody === "3"){
    $TypeOptions = "best";
}

echo $TypeOptions;
[Running] php "test.php"
good