PHP PHP Variable & Types

PHP Variables

Variables are "containers" for storing information:
Rules for PHP variables:

  • A variable starts with the $ sign, followed by the name of the variable
  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case sensitive ($y and $Y are two different variables)

A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).

Creating (Declaring) PHP Variables

PHP has no command for declaring a variable.
A variable is created the moment you first assign a value to it:

Example:

<?php
    $name = "Tutorial";
    $x = 10;
    $y = 20.5;
?>

PHP is a Loosely Type Language

In the example above, notice that we did not have to tell PHP which data type the variable is. 
PHP automatically converts the variable to the correct data type, depending on its value. 
In other languages such as C, C++, and Java, the programmer must declare the name and type of the variable before using it.

Example:

<?php
    $var = "Tutorial"; //var become String type
    $var = 50;         //var become Integer type
    $var = 20.5;       //var become Float type
?>


Share This Page on:


Ask Question

Basics of PHP