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:
1<?php
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.
1<?php
2$customerName = "Fred";
3$customerID;
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:
1<?php
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:
1<?php
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.
1<?php
2echo $customerName;
Perhaps you would like to make the example more meaningful by adding some text in quotation marks before the variable contents:
1<?php
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.
1<?php
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:
1<?php
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:
1<?php
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

Introduction to JavaScript- Basics

JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer, Firefox, Chrome, Opera, and Safari. What You Should Already Know Before you continue you should have a basic understanding of the following: HTML and CSS If you want to study these subjects first, find the tutorials on our Languages page . What is JavaScript? JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language A scripting language is a lightweight programming language JavaScript is usually embedded directly into HTML pages JavaScript is an interpreted language (means that scripts execute without preliminary compilation) Everyone can use JavaScript without purchasing a license Are Java and JavaScript the same? NO! Java and JavaScript are two completely different languages in both concept and design! Java (developed by Sun Microsystems) is a powerful and much more complex programming language ...

IBM Sample Problem Using Speed

Question 1 A policeman starts chasing a thief 30 minutes after the thief had run from a spot. With an average speed of 20km per hour, he takes 2 hours to catch the thief. What is the average speed of the thief? a)16km/hr b)25km/hr c)24km/hr d)18km/hr Answer : a)16km/hr Solution: As given, the average speed of the policeman = 20km/hr. He takes 2 hours to catch the thief, so from formula, "distance = speed x time" we have The total distance covered by the police to catch the thief = 20 x 2 = 40 km (This value is also equal to the distance run by thief before being caught by Police.) Policeman had started late by 30 minutes and took 2 hours to catch the running thief. Above means that the thief takes (30minutes + 2 hours =) 5/2 hours to reach 40km. So the speed of the thief = 40/(5/2) = 40 x 2 / 5 = 16 km/hr. Hence the answer is 16km/hr. Question 2 From a particular spot, Tom started to chase Jerry which had left the spot before 30 minutes. Tom ran acro...

MCA - Syllabus, Notes, Question Papers, Projects

MCA - Syllabus, Notes, Question Papers, Projects : SEMESTER - 1 Syllabus: Syllabus PDF Notes: Semester 1 Notes Question Papers:  Project: SEMESTER - 2 Syllabus: Syllabus PDF                                   Notes: Semester 2 Notes Question Papers:  Projects:  SEMESTER - 3  Syllabus: Syllabus PDF                                   Notes: Semester 3 Notes Question Papers:  Project: SEMESTER - 4  Syllabus: Syllabus PDF                               ...