PHP scripts start with <?php
and end with ?>
. These tags tell the server to interpret the enclosed code as PHP.
Example
<?php
// PHP code goes here
?>
In a PHP file, you can write both HTML and PHP code. The PHP code needs to be inside the PHP tags.
Echo and Print Statements
echo
and print
are two basic ways to output data in PHP. They are almost identical, with some minor differences.
Using Echo
echo
can output one or more strings.- It’s slightly faster than
print
. - Syntax:
echo "Hello, World!";
Using Print
print
can only output one string and always returns 1.- Syntax:
print "Hello, World!";
Example
<?php
echo "Hello, World!";
print "I'm learning PHP!";
?>
Comments in PHP
Comments are used to explain code and are ignored by the PHP interpreter.
Single-Line Comments
Single-line comments can be made with //
or #
.
<?php
// This is a single-line comment
# This is also a single-line comment
?>
Multi-Line Comments
Multi-line comments start with /*
and end with */
.
<?php
/* This is a
multi-line comment */
?>
Practice Exercise: Try creating a PHP script that uses both echo
and print
to output different strings. Add comments to explain what your script does.
Conclusion: Understanding these basics sets the foundation for your PHP journey. In our next tutorial, we’ll explore variables and data types in PHP.