开发者

PHP if statement?

Hi i wonder what i might be doing wrong. I have two conditions that returns true or false.For same reason it doesnt work. I would appreciate if someone point out what i might be doing wrong.

<?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 restauran开发者_运维问答t";
  }                               
?>

EDIT- Sorry i edit it but didnt show up for some reason. Basically script looks into urls for term "retail" if it finds it, it should return "this is retail" if not "this is restaurant"

quoterequest is a just a variable like so

$quoterequest = "washington"

and the currentpage is driven from

<?php $currentPage = basename($_SERVER['SCRIPT_NAME']);

Just to be clear. Url is structure like so

www.example.com/retail-store.php www.example.com/store.php


$pageType is never true. If the string is contained, strpos returns an integer. So test for !== false.

<?php  
    $pagetype = strpos($currentPage, 'retail');
    if (isset($quoterequest) && $currentPage !== 'index.php') {
        if ($pagetype !== false) {
            echo "this is retail";
        }
        else {
            echo "this is restaurant";
        }
    }                     
?>


At first look it should be $pagetype !== false
strpos return false or a numeric value on match

quote from php.net/strpos

Returns the position as an integer. If needle is not found, strpos() will return boolean FALSE.

so, to check if the value is not found you should use if(strpos(...)===false) and to check if it's found you should use if(strpos(...)!==false)


no sense in duplicating the conditions each time either. The below code should do what you want.. (taking into account the aforementioned strpos comments).

$pagetype = strpos($currentPage, 'retail');
if($currentPage !== 'index.php' && isset($quoterequest)){
   if ($pagetype === false){
     echo "restaurant";
   }else{
     echo "retail"; 
   }
}


PHP has lazy evaluation. If the first term in an if statement evaluates to false, it will stop evaluating the rest of the code. If isset($quoterequest) evaluates to false, nothing else in either of your statements will be examined.

$>
<?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!
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜