What is the out put of the following php string position check?


$str = 'abcdef';

if(strpos($str, 'a')){

echo 'String position found';

}else{

echo 'String position not found';

}

Train Asked on January 7, 2016 in PHP.
Add Comment
  • 1 Answer(s)

    The Answer is, ‘String position not found‘. Strange isn’t it?

    But this is something where every developer must be careful of.

    Since the ‘a‘ is in the 0th position, the condition will be false and jump in to the else part.

    In order to over come this, you should always use the type check there,

     $str = 'abcdef';
     if(strpos($str, 'a') !== false){
     echo 'String position found';
     }else{
     echo 'String position not found';
     }
     
    Train Answered on January 7, 2016.
    Add Comment

    Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.