嗨,我想知道我可能做错了什么。我有两个条件返回true或false。出于同样的原因它不起作用。如果有人指出我可能做错了什么,我将不胜感激。
<?php
$pagetype = strpos($currentPage, 'retail');
if(isset($quoterequest) && $pagetype === True && $currentPage !== 'index.php'){
echo "this is retail" ;
}elseif(isset($quoterequest) && $pagetype === False && $currentPage !== 'index.php'){
echo "this is restaurant";
}
?>
编辑 - 抱歉我编辑它但由于某种原因没有出现。基本上脚本会查找网址“零售”,如果找到它,它应该返回“这是零售”,如果不是“这是餐馆”
quoterequest只是一个像这样的变量
$quoterequest = "washington"
并且当前页面来自
<?php $currentPage = basename($_SERVER['SCRIPT_NAME']);
要清楚。网址是这样的结构
www.example.com/retail-store.php www.example.com/store.php
答案 0 :(得分:6)
$pageType
永远不会成真。如果包含字符串,则strpos返回一个整数。因此,请测试!== false
。
<?php
$pagetype = strpos($currentPage, 'retail');
if (isset($quoterequest) && $currentPage !== 'index.php') {
if ($pagetype !== false) {
echo "this is retail";
}
else {
echo "this is restaurant";
}
}
?>
答案 1 :(得分:1)
首先看它应该是$ pagetype!== false
strpos返回false或匹配时的数值
引自php.net/strpos
以整数形式返回位置。如果未找到needle,strpos()将返回布尔值FALSE。
所以,要检查是否找不到值,你应该使用if(strpos(...)=== false)并检查它是否应该使用if(strpos(...)!== false )
答案 2 :(得分:1)
每次重复条件都没有意义。下面的代码应该做你想要的......(考虑到上面提到的strpos评论)。
$pagetype = strpos($currentPage, 'retail');
if($currentPage !== 'index.php' && isset($quoterequest)){
if ($pagetype === false){
echo "restaurant";
}else{
echo "retail";
}
}
答案 3 :(得分:0)
PHP有懒惰的评价。如果if
语句中的第一项计算结果为false,则它将停止评估其余代码。如果isset($quoterequest)
的计算结果为false,则不会检查任何一个语句中的其他内容。
$>
<?php
function untrue() {
return FALSE;
}
function truth() {
echo "called " . __FUNCTION__ . "\n!";
return TRUE;
}
if ( untrue() && truth() ){
echo "Strict.\n";
} else {
echo "Lazy!\n";
}
$> php test.php
Lazy!