PHP TUTORIALPHP TutorialPHP InstallationPHP Hello WorldPHP Basic SyntaxPHP CommentsPHP VariablesPHP Variable ScopePHP ConstantsPHP StringsPHP OutputPHP Data TypesPHP Type CastingPHP OperatorsPHP ConditionalsPHP Shorthand ConditionalsPHP LoopsPHP Loop Control StructuresPHP FunctionsPHP String FunctionsPHP ArraysPHP Superglobal VariablesPHP in HTMLPHP RegexRegex IntroductionRegex PCRE SyntaxPHP PREG FunctionsPHP FormsPHP Forms IntroductionPHP Forms CreatingPHP Forms SecurityPHP Forms ValidationPHP Forms Required InputsPHP Forms StickyPHP Forms Advanced ValidationPHP Forms FinishingPHP OOPPHP Object Oriented ProgrammingPHP OOP ClassesPHP OOP PropertiesPHP OOP ObjectsPHP OOP MethodsPHP OOP $this KeywordPHP OOP Constructors and DestructorsPHP OOP VisibilityPHP OOP InheritancePHP OOP Abstract Classes and MethodsPHP OOP Interfaces

PHP Variables

Variables are pieces of information stored in the computer's memory.

Variables are used to store information and retrieve them when needed. They can be labeled with a meaningful name to be understood easily by the readers and ourselves.

The data stored in variables can be changed.

What can we do with variables?

We can think a variable as a box.

See the following image.

Variables are like boxes
Variables are like boxes

PHP Variable Naming

As a box can be labeled with a name, similarly, a variable can be (actually, should be) labeled with a name. In PHP, there are certain rules to follow when naming a variable.

Rules for PHP Variables

PHP Variable naming
PHP Variable naming


$name = 'Hyvor'; 	// valid
$_name = 'Hyvor';	// valid - starts with an underscore
$näme = 'Hyvor';  // valid - 'ä' is (Extended) ASCII 228

$1name = 'Hyvor';	// invalid - cannot start with a number
$this = 'Hyvor'; 	// invalid - cannot assign value to $this

Note that the variable names are case-sensitive. $name and $Name are two different variables.

Tip: Always use a meaningful name for a variable.

PHP Declaring Variables

In programming, creating a variable is called declaring. But, in PHP, unlike other programming languages, there is no keyword to declare a variable.

Variables are declared when you assign a value to them
Unlike other programming languages, you do not have to define data types for variables. (Programming languages like this is called loosely typed languages)

Note: Strings should be wrapped with " (double-quotes) or ' (single-quotes). (We will learn more about quoting in PHP Output tutorial.)

When declaring a variable,

PHP Variable Assignment
PHP Variable Assignment

PHP Declaring Variables Example

$month = "May";
$day = 22;

After running this part of the script,

PHP Reassigning Values to Variables

A variable stores the value of its most recent assignment.

The output of the below code is "World" because it is the value of the last assignment of $text.

PHP Reassigning Variables Example

$text = 'Hello';
$text = 'World';

echo $text;

Run Example ››
Facebook Twitter