PHP String Comparison and Formatting Practice Questions with Solution

Introduction

PHP provides useful functions for comparing strings and formatting output. These functions help developers compare product codes, validate text, display employee salaries, and prepare readable reports. In this chapter, you will understand the concepts PHP String Comparison and Formatting Practice Questions with Solution strcmp(), strcasecmp(), strncmp(), strnatcmp(), printf(), sprintf(), and number_format() through solved PHP questions with sample outputs and beginner-friendly explanations.

Question 1: Compare Two Strings Using strcmp()

Problem Statement

Write a PHP program to compare two strings, "PHP" and "PHP", using the strcmp() function.

PHP Solution

<?php
$string1 = "PHP";
$string2 = "PHP";

$result = strcmp($string1, $string2);

if ($result === 0) {
    echo "Both strings are equal.";
} else {
    echo "Strings are different.";
}
?>

Sample Output

Both strings are equal.

Explanation

The strcmp() function compares two strings in a case-sensitive manner.

  • Returns 0 when both strings are equal.
  • Returns a negative value when the first string comes before the second.
  • Returns a positive value when the first string comes after the second.

Concepts Covered

  • strcmp()
  • Case-sensitive string comparison
  • Conditional statements

Question 2: Compare Strings Without Checking Case

Problem Statement

Compare "Marketing" and "MARKETING" without treating uppercase and lowercase letters as different.

PHP Solution

<?php
$department1 = "Marketing";
$department2 = "MARKETING";

$result = strcasecmp($department1, $department2);

if ($result === 0) {
    echo "Both department names match.";
} else {
    echo "Department names do not match.";
}
?>

Sample Output

Both department names match.

Explanation

The strcasecmp() function compares strings without considering letter case. Therefore, "Marketing" and "MARKETING" are treated as equal.

Concepts Covered

  • strcasecmp()
  • Case-insensitive comparison
  • Comparing department names

Question 3: Compare Strings Using the Strict Equality Operator

Problem Statement

Write a PHP program to compare "Rahul123" and "rahul123" using the === operator.

PHP Solution

<?php
$username1 = "Rahul123";
$username2 = "rahul123";

if ($username1 === $username2) {
    echo "Usernames are identical.";
} else {
    echo "Usernames are different.";
}
?>

Sample Output

Usernames are different.

Explanation

The === operator checks whether two values are identical. Since PHP string comparisons using === are case-sensitive, the uppercase R and lowercase r make these strings different.

Concepts Covered

  • Strict equality operator
  • Case-sensitive comparison
  • Username validation

Question 4: Compare Only the First Three Characters

Problem Statement

Compare the first three characters of the product codes "PRD2026" and "PRD1250" using strncmp().

PHP Solution

<?php
$code1 = "PRD2026";
$code2 = "PRD1250";

$result = strncmp($code1, $code2, 3);

if ($result === 0) {
    echo "Product prefixes match.";
} else {
    echo "Product prefixes do not match.";
}
?>

Sample Output

Product prefixes match.

Explanation

The strncmp() function compares two strings up to a specified number of characters. Here, only the first three characters are compared. Both codes begin with "PRD", so the result is 0.

Concepts Covered

  • strncmp()
  • Partial string comparison
  • Product code validation

Question 5: Compare File Names Naturally

Problem Statement

Compare "File2" and "File10" using strnatcmp() so that numbers in the strings are compared naturally.

PHP Solution

<?php
$file1 = "File2";
$file2 = "File10";

$result = strnatcmp($file1, $file2);

if ($result < 0) {
    echo "$file1 comes before $file2.";
} elseif ($result > 0) {
    echo "$file1 comes after $file2.";
} else {
    echo "Both file names are equal.";
}
?>

Sample Output

File2 comes before File10.

Explanation

The strnatcmp() function performs a natural-order comparison. It treats numeric portions of strings in a way that is more intuitive for file names. As a result, File2 comes before File10.

Concepts Covered

  • strnatcmp()
  • Natural-order comparison
  • File name sorting

Question 6: Display Employee Details Using printf()

Problem Statement

Display an employee’s name and salary using the printf() function.

Employee data:

  • Name: Amit Sharma
  • Salary: 45500

PHP Solution

<?php
$name = "Amit Sharma";
$salary = 45500;

printf("Employee Name: %s\n", $name);
printf("Monthly Salary: ₹%d\n", $salary);
?>

Sample Output

Employee Name: Amit Sharma
Monthly Salary: ₹45500

Explanation

The printf() function displays formatted output.

  • %s is used for a string.
  • %d is used for an integer.

The \n character moves the output to a new line.

Concepts Covered

  • printf()
  • Format specifiers
  • Displaying employee information

Question 7: Display Salary With Two Decimal Places

Problem Statement

Display an employee’s incentive of 1250.5 with exactly two decimal places using printf().

PHP Solution

<?php
$incentive = 1250.5;

printf("Employee Incentive: ₹%.2f", $incentive);
?>

Sample Output

Employee Incentive: ₹1250.50

Explanation

The %.2f format specifier displays a floating-point number with two digits after the decimal point. PHP displays 1250.5 as 1250.50.

Concepts Covered

  • printf()
  • Floating-point formatting
  • Decimal precision

Question 8: Store Formatted Text Using sprintf()

Problem Statement

Create an employee message using sprintf() and store the result in a variable.

Employee data:

  • Name: Amit
  • Department: IT

PHP Solution

<?php
$name = "Amit";
$department = "IT";

$message = sprintf(
    "Employee %s works in %s department.",
    $name,
    $department
);

echo $message;
?>

Sample Output

Employee Amit works in IT department.

Explanation

The sprintf() function formats a string and returns it instead of displaying it directly. The formatted message is stored in $message and then displayed using echo.

Concepts Covered

  • sprintf()
  • String formatting
  • Storing formatted messages

Question 9: Format a Large Number With Commas

Problem Statement

Display the number 1250000 with comma separators using number_format().

PHP Solution

<?php
$sales = 1250000;

echo "Total Sales: " . number_format($sales);
?>

Sample Output

Total Sales: 1,250,000

Explanation

The number_format() function formats a number for easier reading. By default, it uses commas to separate thousands and displays no decimal places.

Concepts Covered

  • number_format()
  • Number formatting
  • Sales report presentation

Question 10: Generate a Formatted Employee Salary Report

Problem Statement

Create an employee salary report using sprintf() and number_format().

Employee data:

  • Name: Neha Sharma
  • Department: Finance
  • Monthly Salary: ₹68500

PHP Solution

<?php
$name = "Neha Sharma";
$department = "Finance";
$salary = 68500;

$formattedSalary = number_format($salary);

$report = sprintf(
    "Employee: %s\nDepartment: %s\nMonthly Salary: ₹%s",
    $name,
    $department,
    $formattedSalary
);

echo $report;
?>

Sample Output

Employee: Neha Sharma
Department: Finance
Monthly Salary: ₹68,500

Explanation

First, number_format() adds a comma separator to the salary. Then, sprintf() places the employee name, department, and formatted salary into a single report. Finally, echo displays the report.

Concepts Covered

  • sprintf()
  • number_format()
  • Combining PHP functions
  • Employee salary reports

Key Takeaways

  • strcmp() compares two strings with case sensitivity.
  • strcasecmp() compares strings without considering letter case.
  • strncmp() compares a specified number of characters.
  • strnatcmp() compares strings using natural ordering.
  • === checks whether two values are identical.
  • printf() displays formatted output.
  • sprintf() returns a formatted string that can be stored in a variable.
  • %s represents a string, %d an integer, and %.2f a floating-point number with two decimal places.
  • number_format() makes large numbers easier to read by adding separators.

Frequently Asked Questions

1. What is string comparison in PHP?

String comparison means checking whether two strings are equal or determining their relative order. PHP provides functions such as strcmp() and strcasecmp() for this purpose.

2. What is the difference between strcmp() and strcasecmp()?

strcmp() considers uppercase and lowercase letters different, while strcasecmp() ignores differences in letter case.

3. What does strcmp() return when strings are equal?

It returns 0 when the two strings are equal.

4. What is the purpose of strncmp()?

strncmp() compares two strings up to a specified number of characters.

5. What is strnatcmp() used for?

strnatcmp() compares strings naturally, which is useful when sorting names such as File2 and File10.

6. What is the difference between printf() and sprintf()?

printf() displays formatted output directly, whereas sprintf() returns the formatted string so it can be stored or used elsewhere.

7. What does %s mean in printf()?

%s is a format specifier used to display a string.

8. How can PHP display a number with two decimal places?

Use printf("%.2f", $number) to display a floating-point number with two digits after the decimal point.

9. What does number_format() do in PHP?

number_format() formats numbers using thousands separators and, optionally, a specified number of decimal places.

10. Can sprintf() be used to create reports?

Yes. sprintf() can combine strings and numeric values into formatted messages, making it useful for employee reports, invoices, and sales summaries.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top