Leahcim
Leahcim

Reputation: 42069

Please explain this PHP syntax

I've looked up the functions in the manual, but I still don't get this. According to the person who wrote the code, if the User enters "y" then the function (not shown here) will execute. However, because of the !, it looks to me like the function (not shown here) will execute if the user enters something other than "y".

Please explain (I"m a relative newbie so as much detail as possible would be helpful). Thanks

if(!strncasecmp(trim(fgets(STDIN)),'y',1)) 

Upvotes: 3

Views: 220

Answers (2)

codaddict
codaddict

Reputation: 455460

fgets(STDIN) - reads a string from standard input(keyboard in your case).

trim - removes any spaces surrounding the user input. So if the user enters ' y' or a 'y ', it'll be converted to 'y'

strncasecmp - The user might enter either uppercase Y or lowercase y, this function helps you to compare case insensitive way. Also this function returns 0 if the comparison is successful and then you use the ! (not operator) which changes the 0 to a 1 so that the if test passes.

You could re-write it as:

if(strncasecmp(trim(fgets(STDIN)),'y',1) == 0) 

Upvotes: 10

csl
csl

Reputation: 11368

The function strncasecmp returns 0 if there is no difference between the strings compared, hence the ! to check if they're equal.

Upvotes: 4

Related Questions