Web programming

Syntax in PHP and running your first program

Ngoc Phuong

Ngoc Phuong

2021-02-24 . 131 view

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!";

 

Ngoc Phuong
Ngoc Phuong

Web Developer

Thank you for visiting my website. My name is Ngoc Phuong, and I have over 10 years of experience in website development. I am confident in stating that I am an expert in creating impressive and effective websites. If you need a website designed, please feel free to contact me via email at [email protected].

0 feedback