Login |  Register 
Your Developer Exam showed me just how much there is to PHP.
Ross
 

Formatting text

There is often the situation in software development of wanting to format text, to create a message or show a warning etc. One way to do this would be to concatanate text together. However this is quite a messy solution. So...
echo "An error occured on " . $websiteName . " the error states " . $errorText . " please try to " . $error solution.
A better solution would be to use a formatted string, with sprintf function.
echo sprintf("An error occured on %s the error states %s please try to %s", $websiteName, $errorText, $error solution);
An even simpler way to do this would be to use printf which would print the formatted text straight to the screen, which uses the same format string as sprintf.
printf("An error occured on %s the error states %s please try to %s", $websiteName, $errorText, $error solution);
The %s symbols means that a string argument will appear in that point in the string. The arguments are placed in the order of they are in, in the argument list. So in the above example it means websiteName comes first and then errorText. The number of arguments in the string must match the number of arguments in the function, otherwise an error will be thrown. To use the same argument more than once in a string you can number the arguments as shown below, were the argument name is used twice.
$name = "Tom";
$food = "apple";
printf("%1$s went to the shops to buy a %2$s, which %1$s was very pleased with.", $name, $food);
Formatted strings can also be useful for representing SQL statements, were another feature of formatted strings comes to the fore, specifying types. This allows types to be treated properly.
$type = "C";
$sql = sprintf("SELECT * FROM Users WHERE UserType = '%c'", $type);
This ensures that the $type variable is output as a Char and not anyother type.

Comments to date: 6. Page 1 of 1. Average Rating:
well wisher   6:27am on Tuesday, April 11th, 2017 
somebody hack and shut this site down..
its just a load on servers..
arora   6:26am on Tuesday, April 11th, 2017 
go fuck ass of your own tutorials.
d(・∀・)b   5:45am on Sunday, May 24th, 2015 
Seriously if you guys cant learn this far then please go back to study beginner level.

Good example though.
fucking hell   7:44am on Thursday, April 16th, 2015 
fuck you noobs.
y8   3:56am on Monday, April 6th, 2015 
rftrf
Jiya   2:53am on Tuesday, October 21st, 2014 
No, its not helpful

security image
Written by Dominic Skinner
Last Updated: 2011-10-25 16:00:38