PHP
  1. PHP intro
  2. PHP basics
  3. PHP variables
  4. PHP functions
  5. PHP conditions
  6. PHP loops
  7. PHP arrays
  8. PHP classes & objects
  9. PHP strings
  10. PHP forms
  11. PHP entities
  12. PHP files
  13. PHP include files
  14. PHP date & time
  15. PHP cookies
  16. PHP databases
  17. PHP sessions
  18. PHP summary

PHP variables

Variables are a fundamental concept in many computer languages including PHP and knowing how to work with them is essential knowledge.

This tutorial focuses on:

What is a variable?

A variable is a container which stores information in a computer's memory. The value of a variable can change all throughout a script.

Declaring variables

In PHP, a variable is declared with the $ symbol at the beginning. Declaring a variable without it is incorrect and will generate an error.

Syntax:
$varName
Example:
<?php $penColor; ?>

You can assign a value to a variable at the same time that it is declared. This process is known as initialization.

Example of initializing a variable:
<?php $penColor = "blue"; ?>
Example of declaring a variable and then giving it a value:
<?php $penColor; $penColor = "blue"; ?>

NOTE: The $ symbol should always be used with variable names, not just during declaration!

Although the variable name is declared the same way for numeric and text variables, the actual value is not. For text variables, the value is sorrounded by double quotes, while for numeric variables the value does not have double quotes around it.

Example:
<?php //declare a text variable and assign a value to it $penColor = "blue"; //declare a numeric variable and assign a value to it $age = 20; ?>

NOTE: Sorrounding the value of a numeric variable with double quotes is a common error, this makes it a text variable. The value of a numeric variable should never be sorrounded by double quotes!

Naming variables

When naming variables, several rules should be followed:

Printing variables

Variables are printed by including the variable name in double quotes or without double quotes using the print or echo command.

Example:
<?php $color = "blue"; $numChairs = 5; print $color; echo "<br />$numChairs"; ?>
Output:
blue
5

You can also print variables together with regular text. To do this, use the dot ( . ) character to join the text and variable values together.

Example:
<?php $teamName = "The Penguins"; $teamState = "Connecticut"; $numWins = 12; $numLosses = 2; print "The name of the team is " . $teamName; print "<br />The team is from " . $teamState; print "<br />" . $teamName . " have won " . $numWins . " games and have lost " . $numLosses . " games"); ?>
Output:
The name of the team is The Penguins
The team is from Connecticut
The Penguins have won 12 games and have lost 2 games
© Copyright 2013-2014 Landofcode.com
Terms of use | Privacy policy | Copyright information