User:Draicone/Sandbox for Variables in PHP

Variables, as mentioned briefly in Introduction to PHP, are significant for any programming language. They can be used to store all forms of data, and are generally required to perform multiple manipulations on data not hard-coded into a script. This lesson will introduce the basics of variables in PHP.

Basic syntax
In PHP, all variables are denoted by the $ at the beginning of their identifier. They do not need to be declared; they can simply be assigned a value and used from there on. Variables name should start with a lowercase letter; this is not required but (in certain php configurations) prevents clashes with autoglobals (which will be explained later). Here is a basic example of assigning a value to a variable and printing its value onto the page:



Variable conversion
PHP also automagically switches variable types when needed. For example, all strings (a string is a series of characters) must be enclosed in quotes (both single quotes and double quotes are supported). However, sometimes values you fetch from external sources will be strings by default but need to be treated as ints (short for integers, which are numerical values) for the purpose of a calculation. This example shows how it can be done:



In this instance, we are multiplying the number 42 (in a string variable) by pi to a certain number of decimal places (a float variable - you will learn about this later). Conversion can only occur when possible, however - the following will not work:



As '4string2' is not a number, PHP will fail to convert it (in order to be multiplied by pi, which returns a floating point value) and (most likely) return an error or post a warning (depending on PHP's configuration settings in the php.ini file).

Variable types
These are the main types of variables you will be dealing with:


 * int - Short for integer. Holds any integer, i.e. a whole numerical value (no decimal places - however, if an int is assigned a number with a decimal place, it will be converted to a float automatically)
 * float - Abbreviation of floating point value. Holds any integer WITH a decimal place, to a certain precision (generally 32 digits)
 * double - Abbreviation of double precision floating point. Same as above except with far more precision - however, a double value also takes up twice as much memory (generally 8 bytes - obviously insignificant on modern servers)
 * string - Holds any array of characters, i.e. a sentence (or two). Generally has an infinite length; however, for compatibility with older servers, limit the size of strings to 32768 characters.