PHP Tutorial Tutorials - PHP Variables

PHP Variables

A variable in PHP is just like a container to store the data.
Every variable has a name and a value(data)

Variable declaration

  • Starts with a dollar($) sign, followed by the variable.
  • Must start with a letter or underscore "_".
  • Only be comprised of alpha-numeric characters and underscores. a-z, A-Z, 0-9, or _ .
  • Should not contain whitespace(spaces,tabs)
  • Variable is assigned with the = operator. $variable_name = Value; ie:$num = 3;
  • Variable can, but does not need, to be declared before assign a value to it. PHP can automatically converts the variable to the correct data type, depending on its value.
  • Variable names in PHP are case-sensitive. the variables $num, $Num and $NUM are treated as three different variables.

Variable declaration examples

    $num;
    $_total;
    $count = 3;
    $string_1;
    $str_find;
    $date_time;
    $dateTime;

Invalid variable declaration examples

    num; // error, variable should start with $
    $3point; // error, Variable name must start with a letter or underscore "_".
    $date-time; // error,Only be comprised of a-z, A-Z, 0-9, or _
    $date time; // error, Should not contain whitespace
    $total = 98;
    echo $TOTAL; // error,$total and $TOTAL are two different variables

Declare a variable begin with number, will cause a syntax error, for example: $3point;
Parse error: syntax error, unexpected '3' (T_LNUMBER), expecting variable (T_VARIABLE)

Assigning Values to Variables

The assignment operator (=) used to assign value to a variable.

$count = 1;// assign a value when declared

$num; 
$num = 30; // assign value to a variable declared previously
Date:2019-09-30 18:09:03 From:www.Lautturi.com author:Lautturi