How to Name a PHP Variable - dummies

By Steve Suehring, Janet Valade

Variables are containers used to hold information. PHP variables have a name, and information is stored in the variable. For instance, you might name a variable $age and store the number 12 in it. Information stored in a variable can be used later in the script. One of the most common uses for variables is to hold the information that a user types into a form.

When you’re naming a variable, keep the following rules in mind:

  • Identifier: All variable names have a dollar sign ($) in front of them. This tells PHP that it is a variable name.

  • Beginning of name: Variable names must begin with a letter or an underscore. They cannot begin with a number.

  • Acceptable length: Variable names can be any length.

  • Acceptable characters: Variable names can include letters, numbers, and underscores only.

  • Case sensitivity: Uppercase and lowercase letters are not the same. For example, $firstname and $Firstname are not the same variable. If you store information in $firstname, for example, you can’t access that information by using the variable name $firstName.

When you name variables, use names that make it clear what information is in the variable. Using variable names like $var1, $var2, $A, or $B doesn’t contribute to the clarity of the script. Although PHP doesn’t care what you name the variable and won’t get mixed up, people trying to follow the script will have a hard time keeping track of which variable holds what information.

Variable names like $firstName, $age, and $orderTotal are much more descriptive and helpful.