0
0
PhpHow-ToBeginner · 3 min read

How to Use print in PHP: Syntax and Examples

In PHP, you use print to output text or variables to the screen. The syntax is print 'text'; and it sends the text inside quotes to the browser or console.
📐

Syntax

The print statement in PHP outputs a string or variable to the screen. It takes one argument, which is the text or variable you want to display. You must end the statement with a semicolon ;.

  • print: keyword to output text
  • 'text': the string to display, enclosed in quotes
  • ;: ends the statement
php
print 'Hello, world!';
Output
Hello, world!
💻

Example

This example shows how to use print to display a simple message and a variable's value.

php
<?php
$message = 'Welcome to PHP!';
print $message;
print "\n";
print 'This is printed using print statement.';
?>
Output
Welcome to PHP! This is printed using print statement.
⚠️

Common Pitfalls

Common mistakes when using print include forgetting the semicolon, not using quotes for strings, or trying to print multiple items without concatenation.

Remember, print can only take one argument, so you must join strings and variables with the dot . operator.

php
<?php
// Wrong: missing semicolon
// print 'Hello world'

// Wrong: multiple arguments
// print 'Hello', ' world';

// Right: use concatenation
print 'Hello' . ' world';
?>
Output
Hello world
📊

Quick Reference

  • print 'text'; - outputs text
  • print $variable; - outputs variable value
  • print 'Hello ' . $name; - concatenate and print
  • Always end with a semicolon (;)

Key Takeaways

Use print to output text or variables in PHP.
Always end print statements with a semicolon.
Use quotes around strings and concatenate multiple parts with the dot operator.
print accepts only one argument at a time.
It is a simple way to display messages or variable values on the screen.