In PHP, the `strncmp()` function is used to compare the first N characters of two strings and return the comparison result. This is especially useful when you need to match string prefixes exactly. Unlike `strstr()`, which performs partial matching, `strncmp()` compares the full beginning of two strings up to the specified length.
The function accepts three parameters: the first string to compare, the second string, and the number of characters to compare.
In the above code, we compare the first three characters of the strings 'apple' and 'banana'. Since the ASCII value of 'a' is 97 and 'b' is 98, the result is -1 because 97 is smaller than 98. If we compare only the first two characters, the result would be 0 because 'ap' and 'ba' have equal ASCII values.
`strncmp()` can be used to safely compare plain-text passwords with hashed passwords. In this case, hashed versions of passwords are often stored on the server, and plain-text passwords are hashed during comparison for validation.
In the above code, we compare the user's entered password with the hashed password retrieved from the database. If the result is 0, the passwords match, and the output will be 'Password match'. If not, the output will be 'Password does not match'.
Sometimes, we need to compare the contents of two files. `strncmp()` can be used for this task as well. The following code example demonstrates how to compare the content of two files:
In this example, we compare the contents of two text files. If the contents are identical, the result is 0, otherwise, a non-zero result is returned.
Although `strncmp()` is primarily used for string comparison, we can convert arrays to strings and then compare them. This can be done by using `json_encode()` to convert an array to a JSON string, and then applying `strncmp()` to compare them.
In this example, we convert two arrays to JSON strings and use `strncmp()` to compare them. If the array contents are identical, the result is 0.
The `strncmp()` function in PHP is a very useful tool that allows developers to compare strings, file contents, and even arrays. By using `strncmp()` effectively, we can simplify our code, increase efficiency, and ensure secure password comparison and content matching in a variety of use cases.