Basic PHP Syntax.
A PHP script can be placed anywhere in the document.
A PHP script starts with and ends with
?>
:
The default file extension for PHP files is ".php
".
A PHP file normally contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP function "echo
" to output the text "Hello World!" on a web page:
- Example
<!DOCTYPE html>
<html>
<body><h1>My first PHP page</h1>
echo "Hello World!";
?></body>
</html>
PHP Case Sensitivity.
In PHP, keywords (e.g. if
, else
, while
, echo
, etc.), classes, functions, and user-defined functions are not case-sensitive.
In the example below, all three echo statements below are equal and legal:
- Example
<!DOCTYPE html>
<html>
<body>
ECHO "Hello World!
";
echo "Hello World!
";
EcHo "Hello World!
";
?></body>
</html>
PHP Variables
In PHP, a variable is declared using a $ sign followed by the variable name. Here, some important points to know about variables:
- As PHP is a loosely typed language, so we do not need to declare the data types of the variables. It automatically analyzes the values and makes conversions to its correct datatype.
- After declaring a variable, it can be reused throughout the code.
- Assignment Operator (=) is used to assign the value to a variable.
Rules for declaring PHP variable:
- A variable must start with a dollar ($) sign, followed by the variable name.
- It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
- A variable name must start with a letter or underscore (_) character.
- A PHP variable name cannot contain spaces.
- One thing to be kept in mind that the variable name cannot start with a number or special symbols.
- PHP variables are case-sensitive, so $name and $NAME both are treated as different variable.