0
0
PHPprogramming~5 mins

String comparison functions in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the PHP function strcmp() do?

strcmp() compares two strings exactly and returns:

  • 0 if both strings are equal
  • A negative number if the first string is less than the second
  • A positive number if the first string is greater than the second
Click to reveal answer
beginner
How is strcasecmp() different from strcmp()?

strcasecmp() compares two strings ignoring case differences, while strcmp() is case-sensitive.

Click to reveal answer
intermediate
What does strncmp() do in PHP?

strncmp() compares up to a specified number of characters from two strings. It returns 0 if the compared parts are equal.

Click to reveal answer
beginner
Explain the return values of strcmp() with an example.

Example: strcmp('apple', 'banana') returns a negative number because 'apple' is less than 'banana' alphabetically.

Return values:

  • 0 if equal
  • <0 if first string < second string
  • >0 if first string > second string
Click to reveal answer
beginner
Why use strcasecmp() instead of strcmp()?

Use strcasecmp() when you want to compare strings without caring about uppercase or lowercase letters, like comparing user input where case should not matter.

Click to reveal answer
What does strcmp('Hello', 'hello') return?
A0
BA positive number
CA negative number
DBoolean true
Which function compares strings ignoring case?
Astrcasecmp()
Bstrncmp()
Cstrcmp()
Dstrncasecmp()
What does strncmp('apple', 'apricot', 3) return?
ABoolean false
BPositive number
CNegative number
D0
Which function compares only the first N characters of two strings?
Astrncmp()
Bstrcmp()
Cstrcasecmp()
Dstr_replace()
If strcmp($a, $b) returns 0, what does it mean?
A$a is less than $b
B$a and $b are equal
C$a is greater than $b
DComparison failed
Describe how strcmp() works and what its return values mean.
Think about how two words are ordered in a dictionary.
You got /4 concepts.
    When would you use strcasecmp() instead of strcmp()?
    Consider comparing names or emails where uppercase and lowercase letters should not matter.
    You got /3 concepts.