Variables and Data Types in PHP

Variables in PHP

Variable is a named memory location used to store values that can be changed. In other words, values of variables can vary and are not fixed.

How to create variables in PHP?

In PHP we can create variables using dollar($) sign followed by variable name.

Example: $var is a valid variable in PHP. You can choose any name for your variable but with some followed rules.

Rules for naming variables in PHP

  • Variable names should begin with a '$' sign.
  • Variable name can include alphanumeric characters.
  • Only special charater allowed in variable name is underscore(_).
  • Numbers cannot be used as first letter in variable names. However you can begin your variable name with alphabets or underscores.
  • Also variables are case sensitive. It means $var, $Var and $VAR are all different variables.

Examples of valid variable names:

$var, $var1, $var_1, $_var

Use meaningful variable names not too long not too short.

Data Types in PHP

Data Types decides what type and size of value should be stored in a variable. PHP is loosly typed language. It means you don't have to explicitly define the data type. PHP parsor decides it automatically while executing PHP code. If you are familiar with java or C, you must have seen that in Java or C you have to define variables with proper data types.

PHP supports following data-types:

Scalar Types - Scalar data types allow only one value to store within variable.
Here's a list of scalar types.

Data Type Description Example
boolean Possible values are true or false. true
integer Signed integer numbers. 48, -34
floating point numbers Signed decimal numbers. 12.34, -14.001
string group of characters form string and are always enclosed in single quotes or double quotes. 'hi', "hello"

Compound Types - Compound data types allow multiple values to store within a variable.
Following are compound types.

Data Type Description
Array group of similar data types stored in contiguour memory location.
Objects group of variables and methods.
Special Types
Data Type Description
resources it stores references to external resources used during execution of a script.
NULL

It simply means the the variable is holding nothing. It has no value assigned. Also an unset variable is having a value of NULL.

NULL is actually a constant. If you try to echo NULL you will get nothing.

We will discuss compound types later. But lets just create a program defining few variables and displaying them.

Defining and displaying variables
<?php
#defining variables
$int = 9;
$float = 10.2;
$bool = true;
$str = "This is a string.";
$null = NULL;

#displaying variables
echo $int;
echo "<br />";
echo $float;
echo "<br />";
echo $bool;
echo "<br />";
echo $str;
echo "<br />";
echo $null;
?>
<< Comments and Instruction Separator Functions in PHP >>