Skip to main content

Variables in PHP - Create, Assign, Display

A variable is used in PHP scripts to represent a value. As the name variable suggests, the value of a variable can change (or vary) throughout the program. Variables are one of the features that distinguish a programming language like PHP from markup languages such as HTML.
Variables allow you write your code in a generic manner. To highlight this, consider a web form which asks users to input their name and favorite color.

Every time the form is completed, the data will be different. One user may say his name is John and his favorite color is blue. Another may say her name is Susan and her favorite color is yellow. We need a way of working with the values a user enters. The way to do this is by using variables.
There are a few standard variables that PHP creates automatically, but most of the time variables are created (or declared) by you, the programmer. By creating two variables called $name and $color, you could create generic code which can handle any input values. For John, this code:
2echo "Hello, $name. Your favorite color is $color.";
would display:
Hello, John. Your favorite color is blue.
On the other hand, Susan would see:
Hello, Susan. Your favorite color is yellow.
We will look into variable names and displaying the value of variables in the rest of this article, but the important point now is to understand how the use of generic variables can make processing data easy.

Creating Variables

In PHP, simply writing the name of a variable for the first time in a script will create it. There’s nothing extra you need to do. The variable name has to follow some standard rules, though:
  1. The name starts with a $ sign
  2. The first character after the $ must be a letter or underscore
  3. All subsequent characters can be a combination of letters, numbers and underscores
$customerName is a valid variable name because it observes all three rules above.
$123customer is not valid because it violates the second rule, the first character after the $ sign must be a letter or underscore.
It’s a good idea to give your variable a meaningful name. If the data you will be storing is a customer’s name, a sensible name might be $customerName. You could also call it $abc123, but I hope you agree that the former suggestion is better.
There are different conventions you can follow when writing variable names. Regardless of what you choose, it is important to be consistent and follow the convention throughout your script. For example, you can use an underscore to separate words (e.g. $customer_name), or use capital letters to differentiate words, a style called Camel Case (e.g. $customerName).
You are allowed to use both upper and lower case letters when naming a variable, but be aware that $CustomerName is not the same as $customerName. PHP will treat the two as different variables! This reinforces the need to stick to a naming convention.

Assigning Variables

Now that you know you can have PHP create a new variable anytime you need it just by writing a new name, let’s look at another example to learn about assigning values to them.
2$customerName = "Fred";
4$customerID = 346646;
5$customerName = $customerID;
First, the variable $customerName is given the value “Fred”. This is referred to as assigning a value. And because this is the first time $customerName is used, the variable is created automatically. Anytime you write $customerName after that, PHP will know to use the value “Fred” instead.
Then, $customerID is written. A variable can be created without assigning a value to it, though this is generally not considered to be good practice. It is better to assign a default value just so you know it has a value. Remember, variables are variable, so you can always change the value later. Afterwards, the variable $customerID is assigned the value 346646.
Finally, the value of $customerID is assigned to $customerName. You can assign the value of one variable to another; in this case the value of $customerID (346646) overwrites the value in $customerName (“Fred”) so that both variables now represent 346646!
Notice how the types of data referenced by a variable have different “types.” This property is called the data’s data type. “Fred” is given with quotation marks, so it is a string (string is just a fancy name for text). 346646 is obviously a number (more specifically, an integer).
Here are some examples of assigning values with different data types:
2$total = 0;                              // Integer
3$total = "Year to Date";                 // String
4$total = true;                           // Boolean
5$total = 100.25;                         // Double
6$total = array(250, 300, 325, 475);      // Array
Now that you understand the basics of naming variables and assigning values, let’s look at this example and see if you can work out the answer:
2$firstNumber = 4;
3$secondNumber = 6;
4$result = $firstNumber + $secondNumber;
The examples in the previous section showed that values to the right of the = sign are assigned to the variable name on the left of the = sign, so the value 4 is assigned to $firstNumber.
Have a close look at the last line. Though I haven’t explained it previously, the + sign is an operator, in this case performing addition. So what do you think the value will be in $result?
If your answer is 10 then well done, that’s correct! If not, have a look at the example again and read the explanation carefully.

Displaying the Value of Variables

As you saw at the beginning, you can display the value represented by a variable using echo. You can also use print if you’d like, as there is little difference between the two at this point besides less typing with echo.
2echo $customerName;
Perhaps you would like to make the example more meaningful by adding some text in quotation marks before the variable contents:
2echo "Customer name = " . $customerName;
The dot between the text in quotation marks and the variable name is the concatenation operator. It joins the string and the value of the variable together.
You could avoid using concatenation and make use of interpolation instead. Interpolation is when the variable name appears in a string and is replaced by its value instead. Taking advantage of this can sometimes make your code easier to read.
2echo "Customer name = $customerName";
PHP automatically performs interpolation on strings that are enclosed by double-quotation marks. If you wish to display the name of the variable with your text, you can use a backslash immediately before the variable name:
2echo "\$customerName has the value: $customerName";
Alternatively, PHP will not perform interpolation on strings that are enclosed by single-quotation marks. So this is an equally effective statement:
2echo '$customerName has the value: ' . $customerName;
For more information about variables, check out the PHP documentation. You’ll review everything you’ve learned here, and learn about what special variables PHP will automatically define and make available to your scripts, how a variable is bound to the context in which it was declared, and even how variables can be used as the names for other variables!

Popular posts from this blog


Agricultural Research Service

Eligibility Test/ Senior Research Fellowship Examination 

The Agricultural Scientists Recruitment Board (ASRB)
 holds a Competitive Examination for recruiting Scientists of the ARS in the pay scale of Rs. 8,000-13,500 in the ICAR Institutes, combined with National Eligibility Test (NET) for recruitment of Lecturers and Assistant Professors by the State Agricultural Universities (SAUS) and for award of ICAR Senior Research Fellowships.

The selected candidates for Agricultural Research Service must serve in the institutes to which they are posted until they find appointment for higher positions through selection at other institutes.

(i) Candidates successful in ARS are appointed as Scientists in the Indian Council of Agricultural Research in the pay scale of Rs. 8,000-13,500.

(ii) Candidates clearing the National Eligibility Test are recommended to various State Agricultural Universities who will consider them for appointment as Lecturers or Assistant Pro…


The Union Public Service Commission (U.P.S.C.) conducts Civil Services' Examination once a year in two stages. The Preliminary Examination (Objective Type) for selection of candidates for the Main Examination is held in the month of May.

The Civil Services Main Examination
 is held in the months of October/November. Blank application forms and other particulars are published in the Employment News, generally in the month of December.

The last date for the submission of applications to the Secretary, Union Public Service Commission, Dholpur House, Shahjahan Road, NewDelhi-11001 1 is usually the last week of January of the year of examination.

The Combined Civil Services Examination is conducted for Recruitment to the following Services/Posts:

1. Indian Administrative Service.
2. Indian Foreign Service.
3. Indian Police Service.
4. Indian P & T Accounts & Finance Service, Group 'A'.
5. Indian Audit and Accounts Service, Group 'A'.
6. Indian Customs and Central Excise S…

Aptitude Test Practice Questions - With Answers

Question 1. Which of the following is least like the others?
A.    cube
B.    sphere
C.    pyramid
D.    circle

D (because the circle is the only two-dimensional figure)

Question 2. Consider a language which uses the following set of characters:
Small set: { a b c }
Large set: { A B C }
Punctuation set: { x y }
This language must follow the following rules:
  1.    A punctuation character must end all series.
  2.    A series can have up to but no more than 4          characters,including punctuation characters.

Does the following series follow all the rules of the language defined above?
  A.    Yes
  B.    No

A (the series has only four characters and ends in a punctuation character)

Question 3. Consider the following flow chart for a customer:

The person in No.1 is:
    A.   Married, with children
    B.   Married, with at least one son
    C.   Unmarried, with at least one daughter
    D.   Unmarried, with at least one son
    E.   Unmarried, with no children