You will learn in this tutorial how to use variables in PHP and manipulate their data.


First thing to know is that PHP variables are always marked by $, followed by the variable name (example: $variable).

 

  • Variable names

The name can include a pretty wide range of characters, but it is recommended to use alphanumericals and underscore (ex: _) as a separator. Another good tip is to use caps to separate words in complex variable name (ex: $returnedData).

A variable name
-  can’t start with a digit, though it can start with underscore;
- can’t have spaces or “-”;
-  can start with underscore;
-  IS case sensitive;

1
2
3
4
5
6
7
8
9
10
11
12
<?php

$variable = 12;
$var1 = "foo";
$_name = 23;
$test_name = "bla";
$anotherTestName = 0;
// all the above are valid

$1var = "blank";
// invalid
?>

PHP variable name

  • Variable types

There are four variable types: boolean (1 or 0, TRUE orFALSE), integer (ex: 10, 4, -6), float (ex: -0.54236, 54.0, -6) and string (ex: “example of string”).

A useful feature of PHP is that variables are very flexible. You can use them with any type you like, integer, float and then string, or whatever you like. It doesn’t matter, the parser changes it’s type automatically. This helps you write more code in less time, and you can also recycle the variables, and use them in more than one purpose, saving server side memory consumption.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php

$variable = 12;
echo "integer: $variable<br />";

$variable = "test string";
echo "string: $variable<br />";

$variable = -0.5563;
echo "float: $variable<br />";

// example of using a variable with changing type

?>

PHP variable types

Leave a Reply

Security Code:
Captcha reload captcha

Looking for something?
Archives
Blogroll