In this article, I will provide a brief introduction to the syntax in PHP and guide you on how to run your first program to help you familiarize yourself with PHP.

I. Basic Syntax in PHP

1. Syntax in PHP

A segment of PHP code can be inserted anywhere in a document.

<!--?php
// Đoạn mã PHP nằm trong đây!
?-->

A PHP code segment begins with ?>

The file extension of a PHP file is .php

Usually, PHP code is coupled with HTML.

Example

<!DOCTYPE html>
<html>
<body>

<h1>Trang PHP đầu tiên của tôi</h1>

<?php
echo "Chúc bạn hạnh phúc!";
?> 

</body>
</html>

Note: PHP statements end with a semicolon (;).

2. Echo and print statements in PHP

In PHP, there are two fundamental ways to display data on the screen - echo and print.

The difference between echo and print:

  • Echo: can output one or more strings.
  • Print: outputs a single string and always returns 1.

When it comes to speed, echo is faster as it does not have a return value, while print does return a value, which is 1.

Example

<!--?php
 echo 'A','B','C'; // output multiple strings
 print 'A'; // output only one string
?-->

II. Case-Sensitivity in PHP

In PHP, keywords (like if, else, while, echo, etc.), classes, functions, and user-defined functions are not case-sensitive.

In the following example, all three echo statements below are correct:

<!DOCTYPE html>
<html>
<body>

<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>

</body>
</html>

Note: In PHP, all variable names are case-sensitive.

See the following example for clarification, in this example there are three different variables, when running only the $color variable is assigned the correct value.

<!DOCTYPE html>
<html>
<body>

<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>

</body>
</html>

III. Comments in PHP

When you program, there will be complex pieces of code that require you to leave comments so later, when you revisit the code, it easy to recall and easier to debug if any errors occur.

PHP supports the following comment styles:

1. Syntax for single-line comments

Use # or // to comment a line in PHP

// Outputs a welcome message:
echo "Welcome Home!";

2. Syntax for multi-line comments

Use /* */ to comment multiple lines in PHP

/*
The next statement will
print a welcome message
*/
echo "Welcome Home!";

 

Ngọc Phương

Web Developer

Thank you for visiting my blog. My name is Phuong and I have more than 10 years of experience in website development. I am confident in asserting myself as an expert in creating impressive and effective websites. Anyone in need of website design can contact me via Zalo at 0935040740.

0 feedback