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 ...

How to prepare for interview? follow the steps.

Interview Preparation  Research is a critical part of preparing for an interview. If you haven't done your homework, it is going to be obvious. Spend time researching and thinking about yourself, the occupation, the organization, and questions you might ask at the end of the interview. Step 1: Know Yourself The first step in preparing for an interview is to do a thorough self-assessment so that you will know what you have to offer an employer. It is very important to develop a complete inventory of skills, experience, and personal attributes that you can use to market yourself to employers at any time during the interview process. In developing this inventory, it is easiest to start with experience. Once you have a detailed list of activities that you have done (past jobs, extra-curricular involvements, volunteer work, school projects, etc.), it is fairly easy to identify your skills. Simply g...

Cognizant Company Profile and it's information for Interview

Website: www.cognizant.com HQ Teaneck, NJ Industry Information Technology Services Size 130K+ Employees, $6B+ Revenue NASDAQ CTSH Competitors Infosys, Wipro, Tata Consultancy Services   About cognizant Cognizant Corporate view: Cognizant is an American multinational IT services and consulting corporation headquartered in Teaneck, New Jersey, United States. Cognizant has been named to the 2010 Fortune 100 Fastest-Growing Companies List for the eighth consecutive year. Cognizant has also been named to the Fortune 1000 and Forbes Global 2000 lists. It has consistently ranked among the fastest growing companies including the 2010 Business Week 50 list of the top-performing U.S. companies, the Business Week Hottest Tech Companies 2010, and the Forbes Fast Tech 2010 list of 25 Fastest Growing Technology Companies In America. Founded: 1994 Headquarters: Teaneck, New Jersey, U.S. Key people:  Francisco D'Souza (President & CEO) Lakshmi Naray...