PHP - 比较两个变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5317003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP - compare two variables
提问by anvd
I have this code
我有这个代码
<?php
ob_start();
header("Content-Type: text/html; charset=ISO-8859-1");
$campo = $_GET['campo'];
$valor = $_GET['valor'];
$hello;
if ($campo == "myPassword") {
if (!preg_match("/^\S{4,12}$/", $valor)) {
echo "Tamanho entre 4 e 12 letras e sem espa?os";
}
else
$hello = $valor; //problem here
echo $hello;
}
if ($campo == "passwordMatch") {
if ($hello != $valor ) {
echo "Passwords don't match";
}
}
?>
?>
so, i need to save a variable (where i put "problem here") and compare below, but this code didn't work and i don't know why
所以,我需要保存一个变量(我把“问题放在这里”)并在下面进行比较,但是这段代码不起作用,我不知道为什么
回答by Bloodshot
I would suggest using to compare strings reference: http://php.net/manual/en/function.strcmp.php
我建议使用比较字符串参考:http: //php.net/manual/en/function.strcmp.php
if(strcmp($str1,$str2)):
endif;
or
或者
if(!strcmp($str1,$str2)):
endif;
and replace your code with this
并用这个替换你的代码
if (!preg_match("/^\S{4,12}$/", $valor)) {
echo "Tamanho entre 4 e 12 letras e sem espa?os";
}
else {
$hello = $valor; //problem here
echo $hello;
}
回答by Jakub
Looks like you have a syntax issue here:
看起来您在这里有语法问题:
if ($campo == "myPassword") {
if (!preg_match("/^\S{4,12}$/", $valor)) {
echo "Tamanho entre 4 e 12 letras e sem espa?os";
} else { // missing bracket
$hello = $valor; //problem here
echo $hello;
} // missing bracket
}
Is that your problem? Your ELSE
was missing an opening {
and closing }
.
那是你的问题吗?你ELSE
错过了开头{
和结尾}
。
ALSO
还
For string comparison, you should use ===
and not a numerical ==
对于字符串比较,您应该使用===
而不是数字==
Details are here:
详细信息在这里:
回答by Robert Morel
I had the same problem, turned out to be white space, I used trim($myVar);
to fix.
我有同样的问题,原来是空白,我曾经trim($myVar);
修复过。
回答by Lightness Races in Orbit
If you're expecting $hello
to survive between page loads, you're out of luck.
如果您希望$hello
在页面加载之间幸存下来,那么您就不走运了。
Instead you'll need to persist the variable between sessionsyourself.
相反,您需要自己在会话之间保留变量。
BTW, the line $hello;
doesn't do anything.
顺便说一句,这条线$hello;
没有做任何事情。
EditThe reason I have assumed that you need sessions is that you set $hello
only when $campo == "newPassword"
, then later expect it to be a certain value only when $campo == "passwordMatch"
. You never change the value of $campo
, and clearly it can't be both. This implies that the two pieces of logic are to run on separate page loads.
编辑我假设您需要会话的原因是您$hello
只设置when $campo == "newPassword"
,然后期望它是某个值仅 when $campo == "passwordMatch"
。你永远不会改变 的值$campo
,很明显它不能两者兼而有之。这意味着这两个逻辑将在单独的页面加载上运行。