Monday, May 18

Given string or char available in the word or not using PHP: strpos() method

Hi Guys,

The problem here is that strpos() returns the starting position index of $str2 in $str1 (if found), otherwise it returns false. So in this example, strpos() returns 0 (which is then obtain to false when referenced in the if statement). That’s why the code doesn’t work properly.

The correct solution would be to explicitly compare the value returned by strpos() to false as follows:

$str1 = 'gamechanger';
$str2 = 'change';
if(strpos($str1,$str2) !== false) {
    echo $str1 . " contains " . $str2 ;
} else {
    echo  $str1 . " does not contain " . $str2 ;
}


Without false condition it will execute the false statement ( else part).

Result

gamechanger contains changer

No comments:

Post a Comment

Backup files to google drive using PHP coding

 Dear All, To backup files to Google Drive using PHP coding, you can use the Google Drive API and the Google Client Library for PHP. Here...