CSC220 strposTest.php

From dftwiki3
Jump to: navigation, search

--D. Thiebaut 14:08, 28 September 2010 (UTC)


<?php
// this simple code illustrates the problem associated with string functions
// that return an integer in some cases, and a boolean in other cases.  The
// problem arises when the integer 0 is returned.  0 is also associated with
// False, but is not a boolean.  
//
// Here strpos will return False if the search is unsuccessful.  If the search
// is successful and the substring happens to be located at position 0, then
// 0 is an int, and does not mean False.  In this case, we have to use ===
// or !== to make sure we compare both the value and the type of the 
// two quantities compared!

$string1 = "hello there!";

$pos = strpos( $string1, "hello" );

//--- the wrong way to test ---
if ( $pos != False ) {
  print "Found string at position $pos\n\n";
}
else {
  print "string not found!\n\n";
}


//--- the right way to test ---
if ( $pos !== False ) {
  print "Found string at position $pos\n\n";
}
else {
  print "string not found!\n\n";
}

?>