Home Linux HTML/CSS PHP React VR T-shirt Shop Blog PHP Fiddle

Intro to PHP: Variables and Constants



Quick Copy Boxes



Values are stored in variables and constants. Each value belongs to one of the datatypes

At the bottom of this page there is a code editor pre-loaded with the lesson's code.

Variables

A variable's value can vary. Say you wrote the code for an online form to choose what people want for dinner. For the main course there are 3 options: Steak, Trout or Veggie Delight. There might be a variable called $mainCourse (in PHP all variables start with a $). $mainCourse would be a variable. There are 3 possible options.


//constants

Constants

Constants are values that will always be the same. Say you wrote the code for people to select their dinner for an even called "Programmers Rock!". You might have EVENT_NAME as a constant. Constants are normally written in all caps, so they stand out.


String: Characters


$gameDev = 'John Romero';


        

$gameDev = 'John Romero'; $gameDev contains a string value. This means the variable contains characters.


Integer: Whole Numbers


$gamesOwnedBy = 3;


        

$gamesOwnedBy = 3; $gamesOwnedBy contains an integer value. An integer is a whole number.


Float: Decimals


$avgDailyHours = 9.5;


        

$avgDailyHours = 9.5; $avgDailyHours contains a float value. A float is a decimal.


Boolean: True or False


$finishedGame = true;


        

$finishedGame = true; $finishedGame contains a boolean value. A boolean has a value of TRUE or FALSE.


Defining a Constant


define('NUMBER_WEEK_DAYS', 7)


          

define('NUMBER_WEEK_DAYS', 7) NUMBER_WEEK_DAYS is a constant whose value will always equal 7.




Watch the video tutorial for this lesson:

PHP: Datatypes, Variables and Constants

If you find my tutorials helpful, please consider donating to support my free web development resources.

The more money I raise, the more content I can produce.

Thank you,
Commander Candy

DONATE

Check out my blog:

Coding Commanders Blog


Coding Commanders Storyline:

Coding Commanders Story

Watch the Coding Commanders LAMP Animation:

Coding Commanders: Episode 1



Applied Assignment

Background:
Imagine you are a game developer. You just started working on a first person shooter game and must define the variables and constants.
Assignment:
For each statement, use PHP to define the variable or constant. Also, identify what datatype you think is appropriate for the variable.
Example:
The player will start the game with 100 health.
$health = 100; (integer)
Statements:
1) There is a 25% chance a treasure cheast contains ammo.
2) When a level is completed a message saying 'Level Complete!' displays.
3) The player may or may not find the secret area.
4) Shooting a zombie is always worth 150 points.
5) When the game starts, the player's weapon is a broken chair leg.



Back to Previous Lesson | Continue to Next Lesson