PHP Variables

Posted by tutor | Posted in PHP Tutorial | Posted on 11-12-2009-05-2008

0

A variable is something whose value can be changing, or the other way round, a variable is used to store some values which are not constant. These values can be anything, like string, any integer value etc.

After declaring a variable you can use it again and again in your script.

Variables are declared using a $ sign. In PHP variables are typed according to the value they contain, so we don’t write any type specifier while declaring a variable.

    $var_name = value;

If you forget putting a dollar sign before the name of a variable, it won’t work in PHP

PHP is a Loosely Typed Language.It internally converts a variable to the same type as the data type of its value. You can declare a variable only when you need one. No previous declaration is needed.

Naming Rules for Variables

PHP has variable declaration rules similar to other programming languages:

  • variable name can only start with a letter or an underscore “_”
  • variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ )
  • variable name can not have spaces. If a variable name is of more than one word, it should be separated with an underscore, or with capitalization
    like “$my_string” or “$myString”

Like other programming languages, variable names in PHP also are case-sensitive, so be sure to use the exact capitalization when using a variable. The variables $a_number and $A_number are different variables in PHP.

White Space

Like HTML, whitespaces are ignored in PHP. You can put any number of whitespaces may be to properly indent your code, and all the whitespaces will be ignored by the PHP interpreter.