Hi,

I don't get why my funcion finds the string even if it doesn't exist in textfile:

function name_exists($name) {

		$f = fopen($this->path, "r");
		//echo $this->path;
		while ( $line = fgets($f) ) {
			
			if(strcmp($line,$name == 0)) {
				echo 'exists';
				fclose($f);
				return TRUE;	//we found it and can stop the function
			
			}
			
		}
		fclose($f);
		return FALSE;
		
	}

Can you help me?

Recommended Answers

All 3 Replies

You've misplaced the parenthesis in this line:

if(strcmp($line,$name == 0)) {

Should of course be:

if(strcmp($line,$name) == 0) {

Another consideration is that you are matching the entire line, so it compares $name against the entire line you are processing in each iteration instead of doing a pattern match. For just matching $name somewhere in $line you should use preg_match().

thank you. I made this and it works:

function name_exists($name) {

		$f = fopen($this->path, "r");
		
		while ( $line = fgets($f) ) {
		
			$arr = explode( "\n", $line );		//remove linebreak before comparing
			
			if(strcmp($arr[0],$name) == 0) {
			
				fclose($f);
				return TRUE;	//we found it and can stop the function
			
			}
			
		}
		fclose($f);
		
		return FALSE;
		
	}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.