PHP Print | Sakala code
Sakala Code 1 year ago
sakalacode #core-php

PHP Print

PHP Print

PHP Print

In PHP, the print statement is another way to output data to the browser, similar to echo. Here are some details and key points about using print in PHP:

Basic Usage

The print statement outputs a string:

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

Differences Between Echo and Print

While echo and print are very similar, there are a few notable differences:

  • Return Value: print always returns 1, making it useful in expressions. echo does not return a value.
  • Parameter Handling: print can only take one argument, whereas echo can take multiple arguments separated by commas.

Using Print with Parentheses

Although parentheses are optional, they can be used for readability:

<?php
print ("Hello, World!");
?>

Print and Variables

You can use print to output the value of variables:

<?php
$greeting = "Hello, World!";
print $greeting;
?>

Mixing Strings and Variables

Just like with echo, you can mix strings and variables. Using double quotes allows variable interpolation:

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

Alternatively, you can concatenate variables and strings using the dot (.) operator:

<?php
$name = "Alice";
print "Hello, " . $name . "!";
?>

HTML within Print

print can be used to output HTML content as well:

<?php
print "<h1>Hello, World!</h1>";
?>

Print in HTML Context

You can seamlessly integrate print within HTML:

<!DOCTYPE html>
<html>
<head>
  <title>PHP Print Example</title>
</head>
<body>
  <?php
  $greeting = "Hello, World!";
  print "<p>$greeting</p>";
  ?>
</body>
</html>

Example with Different Usages

Here’s an example demonstrating various uses of print:

<?php
// Basic usage
print "Hello, World!";

// Using parentheses
print ("Hello, World!");

// Variables
$greeting = "Hello, World!";
print $greeting;

// Mixing strings and variables
$name = "Alice";
print "Hello, $name!";

// Concatenation
print "Hello, " . $name . "!";

// HTML within print
print "<h1>Hello, World!</h1>";
?>

When to Use Print

Preference: Some developers prefer print for its return value, which can be useful in certain contexts, like conditional statements.

Expressions: Since print returns a value, it can be used within expressions or even combined with logical operators:

<?php
$result = (print "Hello, World!") ? true : false;
echo $result; // Outputs 1, since print returns 1
?>


0
415

HTML Form Attribute

HTML forms have various attributes that control how data is submitted where it goes and ho...

1709870648.png
Sakala Code
1 year ago
Php Superglobals Post

Php Superglobals Post

1709870648.png
Sakala Code
1 year ago
HTML Heading

HTML Heading

1709870648.png
Sakala Code
1 year ago

Xml Hello World

Simple “Hello World” program in XML (Extensible Markup Language).

1709870648.png
Sakala Code
1 year ago
HTML strike tag

HTML strike tag

1709870648.png
Sakala Code
1 year ago