Certified PHP Developer Learning Resources Variables

Variables
 


In programming, a variable means a value holder. A variable can hold the same value or the value it holds can get changed during the runtime of a program.

01. 02.
03.$greeting = 'Welcome';
04.
05.$name = 'Ram';
06.echo "$greeting $name";
07.echo '
';
08.
09.$name = 'Ramu';
10.echo "$greeting $name";
11.echo '
';
12.
13.$name = 'Raj';
14.echo "$greeting $name";
15.echo '
';
16.
17.?>

Run above script in web browser and you would see following three lines.

Welcome Ram
Welcome Ramu
Welcome Raj

In this script both $greeting and $name are variables. You can see that $greeting holds the same value throughout the script while value of $name gets changed. We print
tags just to have line breaks in the browser.

Naming Variables
In PHP, all variables should start with $ sign. The part after $ sign is called variable name.

  •     Variable names can only contain letters, numbers and underscores.
  •     A variable name should only start with a letter or an underscore.
  •     Variable names are case-sensitive. That means $Greeting and $greeting are two different variables.

Some good practices in variable naming.
1.$firstName // Correct
2.$first_name // Correct
3.$firstName1 // Correct
4.$_firstName // Correct
5.$first-name // Wrong (Hyphen is not allowed)
6.$4firstName // Wrong (Starts with a number)

 For Support