Wednesday, February 16, 2011

How-TO-search-a-letter-inside-a-string-variable-PHP

Assalamu'alaikum and selamat sejahtera

So,for this very nice morning,we will learn on how to find the position of a letter that inside a string variable.For example,give a string variable:"hi five",and then we want to know the position of 'h'.So,we use strpos(string_to_use, letter_to_find, start).Here is the code:


<?PHP
$slogan = "hi five";
$position = strpos($slogan, "h");
print $position;

?> 

So,start is optional either you want to use it or not.It will print '0' ryte?it is because PHP read the letter 'h' as '0',letter 'i' as '1' ,etc.PHP start with zero when to count.How about we change the letter 'h' to be 'H'...it print nothing ryte?it is because PHP can not find any 'H' in 'hi five'.Logically,'h' is just same with 'H'..lol..it is just different in lower case and upper case.Even a small different can make a different result in PHP.So watch out!Okey so for this case,we can use "===",triple equals,to print the false value(as PHP state that "there is no 'H' in 'hi five' ")  result.Here is the code:

<?PHP
$slogan = "hi five";
$position = strpos(
$slogan,'H');

if ($letter_position === false) {
print "Letter not found " ;
}
else {
print "Letter found";
}


?>


N/NOTE:finding someone??

No comments:

Post a Comment