Variables
Published Jul 31, 2021Updated Oct 31, 2022
Contribute to Docs
Variables store data for later use, and allow their contents to be updated or changed. They’re needed when the same code needs to operate on different values at different times. They’re also used when the same value is needed at multiple places throughout the code.
Declaring a Variable
A variable in PHP begins with the $
sign followed by the variable name. Unlike other languages, a variable is created as soon as you assign a value to it:
<?php$x = 1500;$y = 3.1415;$z = 'cheese';?>
In the above, $x
is assigned the integer 1500
, $y
is assigned the float 3.1416
, and $z
is assigned the string 'cheese'
.
Variable names obey the following rules in PHP:
- Variable names are preceded by
$
. - Variable names must start with a letter or the underscore character.
- Variable names can only contain alphanumeric characters and underscores.
- Variable names are case-sensitive.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn PHP on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Career path
Front-End Engineer
Front-end engineers work closely with designers to make websites beautiful, functional, and fast.Includes 34 CoursesWith Professional CertificationBeginner Friendly115 hours