PHP Variable Naming Rules | Best Practices for PHP Variables
Category: Php
Learn the rules for naming PHP variables. Discover the do's and don'ts, including case sensitivity, reserved keywords, and more to ensure your PHP code runs smoothly.
In PHP, variables are used to store data and must follow specific naming rules. Understanding these rules ensures your code works correctly and is easy to maintain.
✅ PHP Variable Naming Rules:
-
Starts with a Dollar Sign ($): All variables in PHP must start with the $ symbol.
Example: $name -
First Character Must Be a Letter or Underscore: The first character after the $ can be a letter (a-z, A-Z) or an underscore (_).
Example: $first_name, $_POST -
Subsequent Characters: After the first character, the variable name can contain letters, numbers (0-9), and underscores (_).
Example: $user1, $address_line_2 -
No Spaces: Variable names cannot contain spaces. Use underscores or camelCase to separate words.
Example: $user_name or $userName -
Case-Sensitive: PHP variable names are case-sensitive, meaning $Variable and $variable are treated as two different variables.
-
No Reserved Keywords: Avoid using PHP reserved keywords (like echo, if, class, etc.) as variable names.
-
No Special Characters: Variable names cannot contain special characters like @, #, &, or -.
🧠 Example:
$userName = "John"; // Valid variable name
$_POST = "Form Data"; // Valid
$1stName = "Alice"; // Invalid, can't start with a number