Learn PHP 9-Creating Variables in PHP

Posted: November 3, 2010 in PHP

Variables are used to make processes we script out more dynamic. In the programming world the word variable means “a symbolic name associated with a value and whose associated value may be changed”.

PHP has loose data typing, which means we do not have to claim a data type for a variable unless it is explicitly called for. Which usually it is not called for.

DO NOT use a number to start a variable name!

This functionality allows values to be passed around more easily, changed, and even taken through user input as in a web form field. Variables should be used in your scripts when the value of certain information would be able to vary, change, or be transfered.

PHP variables are made by placing a dollar sign [ $ ], and then the name of the variable directly after it. The variable name is case-sensitive. Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. When you create a variable name it should identify the value or purpose in a common sense way without being too long.

It is best to always initialize your variables before using them, because variables that are not initialized have a default value of their type depending on the context in which they are used. And it can also lead to script errors if certain variables are not initialized before a script runs.

Variables should have names that identify them well when you scan your code. Common sense variable naming helps you and others decipher your code after you write it.

Here are examples of valid variable names with prefilled dummy values, and display them on a web page:


// Setting variable names and values upon creation, names cannot start with a number
$age = 37;
$name = "Joe";
$_car_color = "green";

// Now echo the sentence to display in the web browser
echo "My name is $name. I am $age years old and my car is $_car_color.";


The output shown at browser like below :

My name is Joe. I am 37 years old and my car is green.

Initialize variable names and give empty values


// Setting variables with empty values
$d4 = "";
$name1 = "";

Simply initialize the variables 


// Simply initialize the variable names


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s