Learn PHP for Developing Web Application

Learn to build web applications with PHP and MySQL, Start your own blog, e-commerce site. In this tutorial you will learn basic, syntax, examples, functions, loops, cookies, sessions, file handling, data connectivity, etc.

PHP Variables


The main way to store information in the middle of a PHP program is by using a variable.

The most important things to know about variables in PHP

  • All variables in PHP are denoted with a leading dollar sign ($).

  • The value of a variable is the value of its most recent assignment.

  • Variables are assigned with the = operator, with the variable on the left-hand side and the expression to be evaluated on the right.

  • Variables can, but do not need, to be declared before assignment.

  • Variables in PHP do not have intrinsic types - a variable does not know in advance whether it will be used to store a number or a string of characters.

  • Variables used before they are assigned have default values.

  • PHP does a good job of automatically converting types from one to another when necessary.

  • PHP variables are Perl-like.

See this example:

$variablename=value;

PHP Variable: Declaring string, integer and float

Following is the example to store string, integer and float values in PHP variables.

<?php
$str="hello string";
$x=200;
$y=44.6;
echo "string is: $str <br>";
echo "integer is: $x <br>";
echo "float is: $y <br>";
?>

Output:

string is: hello string
integer is: 200
float is: 44.6

PHP Variable: Sum of two variables

<?php
$x=5;
$y=6;
$z=$x+$y;
echo $z;
?>

Output:

11

PHP Variable: case sensitive

In PHP, variable names are case sensitive. So variable name "book" is different from Book, BOOK, BoOk etc.

<!DOCTYPE html>
<html>
<body>
<?php
$book = "red";
echo "This is my " . $book . "<br>";
echo "Ths is Java" . $BOOK . "<br>";
echo "This is PHP " . $BoOk . "<br>";
?>
</body>
</html>

Output:

My car is red
Notice: Undefined variable: COLOR in C:\wamp\www\variable.php on line 4
My house is
Notice: Undefined variable: coLOR in C:\wamp\www\variable.php on line 5
My boat is

PHP Variable: Rules

PHP variables must start with letter or underscore only.

PHP variable can't be start with numbers and special symbols.

<?php
$a="hello"; //letter (valid)
$_b="hello"; //underscore (valid)
echo "$a <br/> $_b";
?>

Output:

hello
hello

Invalid PHP Variables

<?php
$4c="hello";//number (invalid)
$*d="hello";//special symbol (invalid)
echo "$4c <br/> $*d";
?>

Output:

Parse error: syntax error, unexpected '4' (T_LNUMBER), expecting variable (T_VARIABLE) or '$' in C:\wamp\www\variableinvalid.php on line 2