String comparison not working right


So i am trying to compare a string which i got from a text file, with a string from a form. The problem is that the comparison won’t return true. ever! I have also tried if(strcmp($streng,$hotellnavn)==0){return true}, but that doesn’t work either. Can anybody help plz??? :slight_smile:

        function finnesHotellnavniHotell($hotellnavn){
         	echo "$hotellnavn";
        foreach($text as $streng ){
    	    echo $streng. "<br/>";
    	    if($streng==$hotellnavn){ //why wont this compare??
    		    echo "is even";
    		    return true;

    		echo "navnet finnes fra før av";
    	$myfile=fopen("HOTELL.txt", "a+");

    	fwrite($myfile, $tekststreng);


    echo "<h1>Her kan du registrere hotell</h1><br/>";
    echo "<form action='' method='post' onsubmit='return valider()'>";
    echo "Hotell navn<input type='text' name='hotellnavn' id='hotellnavn' onFocus='fokus(this)' onBlur='mistetFokus(this)' onMouseOver='musInn(this)' onMouseOut='musUt()'><br>";
    echo "<input type='submit' name='knapp'>";
    echo "</form>";
    echo "<div id='melding'/>";


The following is from the php documentation for the file() function. See the two places that newlines are mentioned -

Return Values

Returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached. Upon failure, file() returns FALSE .

Note :

Each line in the resulting array will include the line ending, unless FILE_IGNORE_NEW_LINES is used, so you still need to use rtrim() if you do not want the line ending present.

This is all the more reason why data should be stored in a database.


Well, have you dumped the data to see what it contains.
Most likely there is a control char inside the value OR you did not trim the data.
A space is not empty. So, " " is not “” … But, trim(" ") is equal to “” …

Try trimming both first and see if that fixes it.

if(trim($streng)==trim($hotellnavn)) {

Otherwise, dump the characters in each. To do this try these two lines of code:

print_r(unpack("C", $streng));
print_r(unpack("C", $hotellnavn));

This will show an array for each and the actual coding used for each character.
If they do not match, you can see why they do not.

Good luck!


thanks you guys!!! trim() function worked :smiley: