PHP Tutorial
- Introduction to PHP
- Install PHP
- PHP Code
- PHP Echo
- PHP Print
- PHP Echo vs Print
- PHP Variable
- PHP Variable Scope
- PHP $ and $$
- PHP Constants
- PHP Magic Constants
- PHP Data Types
- PHP Operators
- PHP Comments
- Control Statement
Control Statement
- PHP If else
- PHP Switch
- PHP For Loop
- PHP foreach loop
- PHP While Loop
- PHP Do While Loop
- PHP Break
- PHP Continue
PHP Programs
- Pattern Programs
- Numbers Programs
- String Programs
- Array Programs
PHP Functions
- PHP Functions
- Parameterized Function
- PHP Call By Value
- PHP Call By Reference
- PHP Default Arguments
- PHP Variable Arguments
- PHP Recursive Function
PHP Arrays
- PHP Array
- PHP Indexed Array
- PHP Associative Array
- Multidimensional Array
- PHP Array Functions
PHP Strings
- PHP String
- PHP String Functions
PHP Math
- PHP Math Functions
PHP Form
- PHP Form: Get Post
PHP Include
- PHP include & require
State Management
- PHP Cookie
- PHP Session
PHP File
- PHP File Handling
- PHP Open File
- PHP Read File
- PHP Write File
- PHP Append File
- PHP Delete 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:
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:
- Using Heredoc Syntax (Triple Quotes):
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:
outputs:
This string contains an escaped quotation mark "
Printing Variable Value:
You can use print to display the value of a variable:
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.