Php guide

From thelinuxwiki
Jump to: navigation, search


Variables and Datatypes

A variable is a keyword or phrase that acts as an identifier for a value stored in a system’s memory.

Storing Values in a Variable PHP lets you store nearly anything in a variable using one of the following datatypes:

String: Alphanumeric characters
Integer: A numeric value, expressed in whole numbers
Float: A numeric value, expressed in real numbers (decimals)
Boolean: Evaluates to TRUE or FALSE
Array: An indexed collection of data 
Object: A collection of data and methods 

PHP is a loosely typed language, which means it determines the type of data being handled based on a “best guess” principle, as opposed to a strictly typed language such as C, which requires you name datatypes for every variable and function. Consider this code snippet:

$foo = "5"; // This is considered a string
$bar = $foo + 2; // This converts $foo to an integer (outputs 7)

This might seem confusing at first, but it’s actually intuitive and eliminates debugging if you enclose a number in quotes accidentally.


A string is any series of characters enclosed in single (') or double (") quotes, or that you create using special heredoc or nowdoc syntax,

Single-Quote Syntax

doesn’t expand special characters or variables. A backslash doesn't need to be escaped to print it as a regular character.

Double-Quote Syntax

special characters interpreted & variables are expanded (unless escaped)

String Concatenation done with a period (.)

$foo = "This is a " . "string.";
$foo = "This is a ";
$bar = "string.";

both produce

echo $foo . $bar;
This is a string.

PHP is a loosely typed language, it’s not necessary to declare a variable as an integer

Heredoc and Nowdoc syntax skipped...


Because PHP is a loosely typed language, it’s not necessary to declare a variable as an integer; however, if you find it necessary, you can explicitly cast, or force, a value as an integer using the following syntax:

$foo = 27; // No quotes around a whole number always means integer
$bar = (int) "3-peat" // Evaluates to 3, evaluates the numeric value if at the beginning of the string 
$bat = (int) "ten 4"; // Evaluates to 0, because the string doesn't start with a numeric value

Floating point numbers are numbers with decimal values or real numbers. They should not be used in equality comparisons.

A Boolean value is can contain only one of two values: TRUE or FALSE.

Note A string value will always evaluate to 0 unless it starts with a numeric value (such as “10 years”).


Browsers don't interpret newline characters (\n), but php can.