PHP Tutorial
Control Statement
PHP Programs
PHP Functions
PHP Arrays
PHP Strings
PHP Math
PHP Form
PHP Include
State Management
PHP File

PHP Print

Print is a language construct in PHP used to output data to the web page or console. It’s similar to echo, but with some key differences.

Key Points:

  • Output: print can output various data types, including strings, numbers, booleans, arrays, and objects.
  • Single Argument: It can only take one argument at a time. For multiple outputs, you’ll need to use print multiple times or use echo.
  • Return Value: Unlike echo, which has no return value, print returns 1. This allows it to be used in expressions, but it’s not a common use case.
Syntax:
				
					print expression;
				
			

here, expression is the value you want to display.

Example:

				
					$message = "Hello, world!";
print $message;  // Output: Hello, world!

				
			

Here’s how to use the print statement in PHP for various output scenarios:

Printing a Simple String:​

				
					<?php
print "Hello, world!";
?>

				
			

Output:

				
					Hello, world!
				
			

Printing a Multi-Line String:

Similar to echo, you have two options for multi-line strings with print:

  • Using Double Quotes with Newlines:
				
					<?php
$message = "This is a multi-line string.\nIt can span across multiple lines.";
print $message;
?>

				
			
  • Using Heredoc Syntax (Triple Quotes):
				
					<?php
$message = <<<EOT
This is a multi-line string.
It can span across multiple lines.
EOT;

print $message;
?>

				
			

Both methods produce the same output:

				
					This is a multi-line string.
It can span across multiple lines.
				
			

Printing Escaping Characters:

Escaping characters works the same way as with echo:

				
					<?php
print "This string contains an escaped quotation mark \"";
?>

				
			

outputs:

				
					This string contains an escaped quotation mark "
				
			

Printing Variable Value:

You can use print to display the value of a variable:

				
					<?php
$name = "Maruti";
print "Hello, $name";
?>

				
			

Output:

				
					Hello, Maruti
				
			

While print and echo achieve similar functionality, there are some minor differences:

  • echo can take multiple arguments separated by commas, while print accepts only one argument per statement.
  • echo is generally considered slightly faster than print.
  • print returns a value of 1, which can be used in expressions (though this is uncommon).

In most cases, you can choose either print or echo based on your preference.

Scroll to Top