0
0
PhpHow-ToBeginner · 3 min read

How to Declare Variables in PHP: Simple Syntax and Examples

In PHP, you declare a variable by starting with the $ symbol followed by the variable name, like $variableName. You assign a value using the = operator, for example, $age = 25;.
📐

Syntax

To declare a variable in PHP, use the $ sign followed by the variable name. Then use the = sign to assign a value. End the statement with a semicolon ;.

  • $: Indicates a variable.
  • variableName: The name you choose for your variable.
  • =: Assignment operator.
  • value: The data you want to store (number, text, etc.).
  • ;: Ends the statement.
php
<?php
$variableName = value;
?>
💻

Example

This example shows how to declare variables with different types of values and then print them.

php
<?php
$name = "Alice";
$age = 30;
$height = 1.65;
echo "Name: $name\n";
echo "Age: $age\n";
echo "Height: $height meters\n";
?>
Output
Name: Alice Age: 30 Height: 1.65 meters
⚠️

Common Pitfalls

Common mistakes when declaring variables in PHP include:

  • Forgetting the $ sign before the variable name.
  • Using invalid characters in variable names (only letters, numbers, and underscores allowed, and cannot start with a number).
  • Missing the semicolon ; at the end of the statement.
  • Trying to use variables before declaring or assigning them.
php
<?php
// Wrong: missing $ sign
name = "Bob"; // This causes an error

// Correct:
$name = "Bob";
?>
📊

Quick Reference

ConceptDescriptionExample
Variable signAlways start with $$age = 25;
Variable nameLetters, numbers, underscore; no starting number$user_name = "John";
AssignmentUse = to assign value$score = 100;
End statementUse semicolon ;$height = 1.75;
Valid valuesStrings, numbers, floats, booleans$isActive = true;

Key Takeaways

Always start PHP variable names with the $ sign.
Use only letters, numbers, and underscores in variable names; do not start with a number.
End each variable declaration with a semicolon ;.
Assign values using the = operator right after the variable name.
Avoid using variables before declaring or assigning them.