What is a Variable in PHP ?


A variable is a representation of a particular value, such as blue or 19349377. By assigning a value to a variable, you can reference the variable in other places in your script, and that value will always remain the same (unless you change it, which you’ll learn about later).

To create a variable, do the following (in your head):

1. Think of a good name! For instance, if I want to create a variable to hold a username, I name my variable:
username
2. Put a dollar sign ( $ ) in front of that name:
$username
3. Use the equals sign after the name ( = ) to assign a literal value to that variable. Put the value in quotation marks:
$username = “joe”
4. Assigning a value to a variable is an instruction and as such should be terminated with a semicolon:
$username = “joe”;

There you have it—a variable called username with a value of joe. Later in this chapter, you’ll do some exciting things (such as math) with your variables.

Naming Your Variables

As you’ve seen, variables begin with a dollar sign ( $ ) and are followed by a meaningful name. The variable name cannot begin with a numeric character, but it can contain numbers and the underscore character ( _ ). Additionally, variable names are case sensitive, meaning that $YOURVAR and $yourvar are two different variables.

Creating meaningful variable names is another way to lessen headaches while coding. For example, if your script deals with name and password values, don’t create a variable called $n for the name and $p for the password—those are not meaningful names. If you pick up that script weeks later, you might think that $n is the variable for “number” rather than “name” and that $p stands for “page” rather than “password.”

About the author

Being the CEO and Founder of ClecoTech International, Mr. Ashish Prajapati is dedicated towards his aim of mentoring young startups into a full-fledged businesses. He is helping startups from America, Europe, India, and various other countries through proper guidance and the use of latest technologies to develop their innovation and ideas into definite realities.

Leave a Reply

Your email address will not be published.