PHP Basics · Lesson 3 of 8
Strings
Create, combine, inspect, and safely format text in PHP.
Lesson
Strings hold text and are written with single or double quotes. Double-quoted strings interpolate variables, while single-quoted strings keep most characters literal. Concatenation uses the dot operator. For output in HTML, escape untrusted text with htmlspecialchars rather than assuming a string is safe.
The example trims whitespace and escapes the value before it enters markup. Formatting and escaping solve different problems: trim normalizes input; htmlspecialchars protects an HTML text context.
Further guidance
Inspect a value before relying on an implicit conversion. Keep input validation separate from casting, use strict comparisons when type matters, and choose an explicit representation for values such as money or optional data. Try normal, empty, and unexpected inputs so the result is deliberate.
Practice task: Create a fresh example for Strings. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.
Code examples
Strings
PHP
$name = trim(" Maya ");
echo htmlspecialchars("Hello, {$name}!", ENT_QUOTES, 'UTF-8');
Expected output
Hello, Maya!
Key points
- Create, combine, inspect, and safely format text in PHP.
- Validate external data before converting or using it.
- Use strict comparisons when both value and type matter.
Your learning progress
Finish this lesson
Optional practice
PHP playground
This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.
Execution is disabled. No code is sent to a server.