PHP Syntax and Variables — PHP Tags, Data Types, and Variable Rules
In this tutorial, you will learn about PHP Syntax and Variables. We cover key concepts, practical examples, and best practices to help you master this topic.
PHP syntax uses <?php opening tags to switch from HTML to PHP mode, variables prefixed with the dollar sign, and a loose type system that automatically converts between types as needed.
Why It Matters
Every PHP script follows the same syntactic rules. Understanding how tags work, how variables are declared, and how PHP handles types is essential before writing any PHP code. PHP's type juggling, while convenient, causes subtle bugs if you do not understand how it works. Mastering variable scope prevents the common problem of modifying a variable in one place and wondering why it did not change elsewhere.
Real-World Use
WordPress themes and plugins mix PHP and HTML extensively using short open tags. Laravel's Blade templates compile to PHP with the same variable syntax. Every form handler, every login system, and every API endpoint uses the variable and type rules you learn here. At DodaTech, our PHP tools use strict types to prevent type juggling bugs in financial calculations.
What You Will Learn
- PHP opening and closing tags and when to use them
- Variable declaration rules and naming conventions
- PHP data types: integers, floats, strings, booleans, arrays, and null
- Type juggling and type casting
- Variable scope: global, local, static, and superglobals
Learning Path
flowchart LR A[Installation] --> B[Syntax and Variables
You are here] B --> C[Control Flow and Loops] C --> D[Functions] D --> E[Arrays] style B fill:#f90,color:#fff
PHP Tags
PHP code lives inside special tags that tell the Interpreter where PHP starts and ends:
<?php
// PHP code here
echo "Hello, World!";
?>
You can mix PHP and HTML freely:
<!DOCTYPE html>
<html>
<body>
<h1><?php echo "Welcome to my site"; ?></h1>
<p>The current time is <?php echo date('H:i'); ?></p>
</body>
</html>
PHP processes everything between <?php and ?> as code. Everything outside these tags is sent directly to the browser as HTML. This is the fundamental concept that makes PHP different from languages like Python or C -- PHP was designed to be embedded in HTML from the start.
Short Open Tags
PHP also supports <?= as a shortcut for <?php echo:
<h2><?= $title ?></h2>
This is always available in PHP 5.4 and later. It is the preferred way to output a single variable in templates.
Variables
PHP variables always start with a dollar sign followed by the variable name:
$name = "Alice";
$age = 30;
$price = 19.99;
$isActive = true;
Naming Rules
- Variables start with
$followed by a letter or underscore - Remaining characters can be letters, numbers, or underscores
- Variable names are case-sensitive:
$Name,$name, and$NAMEare three different variables - Use meaningful names:
$userEmailinstead of$ue - Follow a consistent convention: camelCase (
$firstName) or snake_case ($first_name)
Variable Assignment
$count = 10; // Direct assignment
$message = "Hello"; // String
$total = $count * 5; // Expression
$ref = &$count; // Reference (not a copy)
The reference operator & creates an alias. Changes to $count also affect $ref and vice versa.
Data Types
PHP supports eight primitive types:
<?php
// Scalar types
$int = 42; // Integer
$float = 3.14; // Float (double)
$string = "Hello, PHP!"; // String
$bool = true; // Boolean
// Compound types
$array = [1, 2, 3]; // Array
$object = new stdClass(); // Object
$callable = function() {}; // Callable
// Special types
$null = null; // Null
// Check types
var_dump($int); // int(42)
var_dump($float); // float(3.14)
var_dump($string); // string(11) "Hello, PHP!"
var_dump($bool); // bool(true)
var_dump($null); // NULL
Expected output:
int(42)
float(3.14)
string(11) "Hello, PHP!"
bool(true)
NULL
Strings
PHP strings can use single quotes or double quotes. The difference matters:
$name = "Alice";
echo 'Hello, $name'; // Hello, $name (literal)
echo "Hello, $name"; // Hello, Alice (variable interpolation)
Double quotes parse variables inside them. Single quotes treat everything literally. For complex expressions, use curly braces:
echo "Hello, {$name}! You are {$age} years old.";
Heredoc and Nowdoc
For multi-line strings, use heredoc (parses variables) or nowdoc (literal):
$html = <<<HTML
<div class="greeting">
<h1>Welcome, $name</h1>
</div>
HTML;
$literal = <<<'EOT'
This is a literal string.
Variables like $name are not parsed.
EOT;
Type Juggling
PHP automatically converts between types depending on context. This is called type juggling:
<?php
$result = "10" + 5; // 15 (string "10" converted to int)
$result2 = "10 apples" + 5; // 15 (PHP reads initial numeric portion)
$result3 = "apples" + 5; // 5 (no numeric portion, treated as 0)
$result4 = "10" . 5; // "105" (concatenation with .)
$result5 = 10 . 5; // "105"
$result6 = "10" == 10; // true (loose equality, types converted)
$result7 = "10" === 10; // false (strict equality, types checked)
var_dump($result, $result2, $result3, $result4, $result6, $result7);
Expected output:
int(15)
int(15)
int(5)
string(3) "105"
bool(true)
bool(false)
This behavior is convenient but dangerous. Always use === and !== for comparisons when the type matters. Use strict type declarations at the top of your files to disable juggling in function parameters.
Type Casting
Force a variable to a specific type:
$value = "42.6";
$int = (int) $value; // 42 (truncates)
$float = (float) $value; // 42.6
$string = (string) 100; // "100"
$bool = (bool) 1; // true
$bool2 = (bool) 0; // false
$bool3 = (bool) ""; // false
$bool4 = (bool) "false"; // true (non-empty string is true!)
Variable Scope
Variable scope determines where a variable is accessible:
<?php
$globalVar = "I am global";
function test() {
$localVar = "I am local";
echo $localVar; // Works
echo $globalVar; // Warning: undefined variable
}
test();
echo $localVar; // Warning: undefined variable
Accessing Global Variables Inside Functions
$config = ["db_host" => "localhost"];
function connect() {
global $config; // Import global into function scope
echo $config['db_host'];
}
// Or use the $GLOBALS array
function connect2() {
echo $GLOBALS['config']['db_host'];
}
Static Variables
Static variables retain their value between function calls:
function counter() {
static $count = 0;
$count++;
return $count;
}
echo counter(); // 1
echo counter(); // 2
echo counter(); // 3
Constants
Constants are like variables but cannot change after definition:
define("SITE_NAME", "DodaTech Tutorials");
const MAX_USERS = 1000;
echo SITE_NAME; // DodaTech Tutorials
echo MAX_USERS; // 1000
Constants are automatically global and accessible from anywhere.
Common Mistakes
1. Forgetting the Dollar Sign
name = "Alice"; // Error: $name expected
Every variable must start with $. This is the most common PHP syntax error.
2. Confusing isset and empty
$value = 0;
if (empty($value)) { /* true, because 0 is empty */ }
if (isset($value)) { /* true, because variable is set */ }
if ($value === null) { /* false, because value is 0, not null */ }
3. Assuming == and === Are Interchangeable
if ("1e0" == 1) { /* true, because "1e0" juggles to 1.0 */ }
if ("1e0" === 1) { /* false, because types differ */ }
4. Not Understanding Variable Interpolation in Strings
$items = 5;
echo "You have $itemss"; // Error: $itemss is undefined
echo "You have {$items}s"; // Correct: "You have 5s"
5. Forgetting That Function Parameters Are Local
function setValue($x) {
$x = 100;
}
$y = 5;
setValue($y);
echo $y; // 5, not 100!
Pass by reference to modify the original: function setValue(&$x).
Practice Questions
What is the difference between single-quoted and double-quoted strings in PHP? Double-quoted strings parse variables and escape sequences. Single-quoted strings treat everything literally.
What is type juggling and why should you use strict comparison? Type juggling converts types automatically in expressions. Strict comparison (===) prevents unexpected conversions and catches bugs.
How do you make a variable accessible inside a function? Use the
globalkeyword, the$GLOBALSarray, or pass the variable as a parameter.What does
var_dump()do? It prints a variable's type and value, including nested structures for arrays and objects.Challenge: Write a script that demonstrates all eight PHP data types, uses strict comparison to verify types, and shows the difference between loose and strict equality.
Mini Project: Profile Card
Create a PHP script that defines variables for a user profile and outputs styled HTML:
<?php
$name = "Alex Johnson";
$role = "Security Engineer";
$company = "DodaTech";
$yearsExperience = 8;
$skills = ["PHP", "Python", "C", "Network Security"];
$isCertified = true;
?>
<div class="profile-card">
<h2><?= $name ?></h2>
<p class="role"><?= $role ?> at <?= $company ?></p>
<p>Experience: <?= $yearsExperience ?> years</p>
<p>Certified: <?= $isCertified ? 'Yes' : 'No' ?></p>
<ul>
<?php foreach ($skills as $skill): ?>
<li><?= $skill ?></li>
<?php endforeach; ?>
</ul>
</div>
FAQ
What is Next
Now that you understand variables and types, proceed to Control Flow and Loops to learn if, else, switch, and loop constructs. Then read Functions to organize your code into reusable blocks.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro