Wednesday, July 7, 2010

Problems With String Variable Comparison

Hey there everyone... Its been really long since I have had the last post on  this blog...
I had just been busy with some work...!

     So lets delve into today's technical discussion. Today we will discuss the issue I had been troubled by, for about 10-15days in my BE project, for which ultimately I had to take some other route to get my work done. I again came across the same problem this day. It is the problem of comparison of two variables which hold some string values. Both the times I came across this problem, I was working with web-programming languages.

   While working today with my personal project, I came across some variables in PHP which held string values in them. I was supposed to take one value from the user (lets say 'string1') and the other from the database (lets say 'string2'). Then I had to compare these two strings. The code is as below.


               if(strcmp($string1,$string2)== 0)
                          echo "Comparison Successful...!!!";
               else           
                          echo"Comparison Failed";

  Here, whatever was the reason, the strings were never evaluated to be equal albeit they had the same values in them. This glitch in the code has pestered many of my friends and BE project guide too. It was today when I was told by someone to use the trim() function inbuilt to PHP to get rid of this problem.

               if(strcmp(trim($string1),trim($string2))== 0)
                          echo "Comparison Successful...!!!";
               else           
                          echo"Comparison Failed";

   The trim(string str) rips the string of the trailing and leading blank space.

Conclusion:
   The reason for such thing happening is still unknown but the closer prediction of mine I can make is the presence and absence of  '\0' while storing the strings in the variables.

Disclaimer: The above conclusion is purely based on my learning and programming experience. If someone figures out the exact reason as to why the discussed problem was occurring, his suggestions and thoughts are cordially welcome in comments.

2 comments:

  1. this is because when u store data in database there might be chances to attached extra spaces to d string.So it is always better while adding data into database u should trim it.

    ReplyDelete
  2. ohh,,,!

    is it so..
    I am quite new to PHP...!
    anyway...Thanks for your useful comment.

    ReplyDelete

LinkWithin

Related Posts Plugin for WordPress, Blogger...

Share This

Share |