Web Development

Introduction to PHP Variables

Intro to PHP Variables

Note these points:

  • each php variable starts with a $ prefix
  • each php variable must start with a letter (numbers aren’t allowed)

Here’s an example of a variable being set:

<?php
$myvariable="i am a variable!";
?>

This sets a variable called $myvariable. Its value is i am a variable!.

Now lets slap this variable on the screen:

<?php
$myvariable="i am a variable!";
echo($myvariable);
?>

This displays, or "echos" the $myvariable‘s value to the screen. Thus, the output would be: i am a variable!.

Variables can also contain numbers, and any other special characters. Heres an example:

<?php
$var=1;
?>

You can also add, subtract, and multiply variables!

<?php
$var=1;
$var2=8;
$sum=$var + $var2;
echo("$sum");
?>

This displays $sum (9) on the screen. The 4th line of the code is where the addition takes place. the + sign between the two variables tells PHP to add them.

If you replace the + with a * sign, it multiplies $var and $var2. If you replace the + with a – sign, it subtracts $var from $var2. If you replace the + with a / sign, it divides $var and $var2.

Enjoy :)

About the author

Written by Vardhan .

Vardhan takes programming as a hobby. He spends most
of  his time on IRC and developing little PHP scripts
to see discover new things about PHP and to enhance
his coding ability. Other than programming, Vardhan
enjoys listening to music and biking.

If you found this post useful you may also want to check these out:

  1. How to Setup and use Printing Variables in PHP
  2. Use Stack Variables Whenever Possible
  3. Develop Rock-Solid Code In PHP: Use Variables Effectively, Part 2
  4. Use Synchronized or Volatile when Accessing Shared Variables
  5. Creating Custom Functions
  6. Using Variable Referencing