Used to format the string and return the string without direct output. The formatted string can be assigned to a variable or used for other processing.
fprintf
Used to format the string and write the result to the specified file stream (such as file, standard output, etc.), it does not return the string, but returns the number of characters written.
// sprintf grammar
string sprintf(string $format, mixed ...$values)
// fprintf grammar
int fprintf(resource $stream, string $format, mixed ...$values)
aspect | sprintf | fprintf |
---|---|---|
Return value | Returns the formatted string | Returns the number of characters written |
Output method | Not output directly, only return strings | Write the formatted string to the specified file stream |
Use scenarios | Need to format the string and use it later (storage, processing, output) | You need to write the formatted content directly to the file or output stream |
Number of parameters | Format string + variable | File Stream Resource + Format String + Variable |
Application scope | Widely, any occasion where strings need to be formatted | File operation, log writing, standard output |
<?php
$name = "Alice";
$age = 30;
$formatted = sprintf("Name: %s, Age: %d\n", $name, $age);
echo $formatted;
?>
In this code, sprintf returns the formatted string to $formatted and outputs it via echo .
<?php
$file = fopen("gitbox.net/uploads/user.txt", "w");
if ($file) {
$name = "Bob";
$age = 25;
fprintf($file, "Name: %s, Age: %d\n", $name, $age);
fclose($file);
} else {
echo "Unable to open the file\n";
}
?>
Here, fprintf writes the formatted string directly into the file stream $file .
Scenarios applicable to sprintf :
You need to format the string but not output directly, such as assigning values to variables, doing string splicing, and passing them into other functions.
It is necessary to dynamically construct the string before output or storage.
Fprintf is suitable for scenarios:
The formatted string needs to be written directly to a file or stream, such as to a log file.
It needs to be output to standard output (such as terminals and consoles), which are commonly used in command line scripts.
Understanding the difference between the two can help you handle string formatting and output more effectively when programming in PHP, avoiding unnecessary waste of resources and code complexity.