Introduction to PHP
PHP (full name: PHP: Hypertext Preprocessor) is an open source general-purpose computer scripting language, especially suitable for web development and embedded in HTML. The syntax of PHP draws on the characteristics of popular computer languages such as C language, Java and Perl, and is easy for general programmers to learn. The main goal of PHP is to allow web developers to quickly write dynamic pages, but PHP is also used in many other areas.
PHP files use the .php extension, as in index.php. PHP code can be embedded directly in HTML.
Usage
In a web application, PHP runs on the server. The PHP interpreter executes the code between <?php and ?>, and the server sends the resulting output to the browser. For example:
Precautions
If a file contains only PHP code or ends with PHP code, omit the final ?> tag to avoid accidental trailing whitespace or newlines in the output. When embedding PHP in HTML, use ?> to return to HTML outside the PHP block.
PHP Comments
Like most programming languages, PHP supports comments. Use // for single-line comments and /* Some text here */ for multi-line comments.
Echo
Use echo to output text or the result of an expression. String literals can be enclosed in double quotes "" or single quotes ''. End each echo statement with a semicolon ;.
Strings output with echo can contain HTML. For example, <br/> inserts a line break in the rendered page.
Variable
As in JavaScript, you can assign values to variables in PHP. PHP variable names begin with a dollar sign $.
Variable names must follow these rules.
| Example | Description | Rules |
|---|---|---|
| $value | Lowercase | ✅ |
| $Value | Uppercase | ✅ |
| $_value | Underscore | ✅ |
| $1value | Starts with a number | ❌ |
Variable names are case-sensitive: $value and $Value refer to different variables, even if they contain the same value.
Variable Naming Tips
Camel Case
Camel case combines words without spaces. The first word starts with a lowercase letter, and each following word starts with an uppercase letter. This makes variable and function names containing multiple words easier to read.
Snake Case
Snake case (as in snake_case) separates lowercase words with underscores.
String Operator
PHP has two string operators. The concatenation operator (.) joins two strings. The concatenation assignment operator (.=) appends the right-hand value to the variable on the left.
Arithmetic Operator
References
Thanks for reading.
Every little discovery leads to another.
Comments
Good ideas don’t end at the last line. What’s on your mind?