PHP print is not exactly a function, but a language construct which prints a single string in the output. Since it is a language construct and not a function, it is not mandatory to use parentheses with its argument list. In this article, we will discuss the PHP print Function. Also, we will discuss a few examples of using it.
Note: The major difference between print and echo is that print only accepts a single parameter. Also, print always returns 1.
print (string $argument);
The PHP print accepts only one parameter. The string or variable you need to print is the input the function. Also, you can concatenate multiple strings and variables in the parameter.
The PHP print always returns 1.
Let’s discuss a few examples of printing variables and strings.
Example 1: Print Simple String
For instance, consider a simple example of printing a string.
<?php print ("This is a simple statement"); ?>
In the above example, the function will simply print the input string.
OUTPUT: This is a simple statement
Example 2: Not Using Parentheses
Similarly, you can avoid using the parentheses for the parameter list.
<?php print "It works without a parentheses too!"; ?>
OUTPUT: It works without a parentheses too!
Example 3: Printing Variables
Also, you can print the value of variables.
<?php $stringVariable = "This is a string variable"; $integerVariable = 10; print $stringVariable; print $integerVariable; ?>
You can print variables by providing the variable as a parameter.
OUTPUT This is a string variable10
Example 4: Printing Array Elements
Similarly, you can print individual array elements. However, you cannot print the whole array using PHP print.
<?php $array = array('a' => 'apple'); print $array['a']; ?>
Also, you can use the PHP print_r Function to print arrays in PHP.
Example 5: Single Quotes Vs Double Quotes
However, there is a difference between using single and double quotes.
<?php $fruit = 'apple'; print 'My favorite fruit is $fruit'; print "My favorite fruit is $fruit"; ?>
The single quote prints the variable name. However, the double quote prints the value of string.
OUTPUT: My favorite fruit is $fruit My favorite fruit is apple
Example 6: Concatenate Multiple Variables/Strings
Similarly, you can concatenate multiple strings and variables while using print. This can be easily done using the dot (.) operator.
<?php $fruit = 'Apple'; $anotherFruit = 'Mango'; print 'My favourite fruits are '.$fruit.' and '.$anotherFruit; ?>
OUTPUT: My favourite fruits are Apple and Mango
Vishesh is currently working as a Lead Software Engineer at Naukri.com. He passed out of Delhi College of Engineering in 2016 and likes to play Foosball. He loves traveling and is an exercise freak. His expertise includes Java, PHP, Python, Databases, Design and Architecture.