PHP Variables Examples

How to declare an integer variable in PHP?

PHP doesn't care about primitive types. You can simple declare a integer variable the way you declare string variables.


$integer_var = 3;
echo $integer_var;

?>

How to concatenate variables in PHP?

You can use the '.' operater in PHP to concatenate two variables.


$integer_var = 3;
$str_var = "apples";

echo $integer_var." ".$str_var;

?>

What is Variable Scope in PHP?

In PHP you can't access a variable which is defined outside its scope. How is scope determined? In a PHP script, variables defined outside functions can't be accessed inside the functions.


$integer_var = 3;

function print_var(){
// this will NOT print 3 since $integer_var is not in the scope of this function
echo $integer_var;
}

print_var();

?>

How to define a global variable in PHP?

If you want variables defined out side the function to be accessed inside the function scope then you have make them global inside the fuction. You can use the global term.


$integer_var = 3;

function print_var(){
global $integer_var;

// echos 3 on the screen
echo $integer_var;
}

print_var();

?>

How to cast variables in PHP?

Casting in PHP works the same as in Java or C++. You write the cast type in brackets before the variable.



$integer_var = 3;

function print_var(){
$integer_var = 3;

// now cated to float
echo (float)$integer_var;
}

print_var();

?>

Allow cast types:
(boolean)
(int)
(string)
(array)
(object)

How to concatenate variables using .=?

You can use the '.' operater in PHP to concatenate two variables.


$str_var = "apples";
$str_var .= " and oranges";
echo $str_var;

?>

The example above outputs "apples and oranges".

PHP Variable type juggling in PHP

PHP doesn't require variables to declared using primitive types. Therefore, juggling between two types doesn't require use of any special function. We can simply do things like...

//string var
$var = "0";

//var is now float
$var += 2.5;

//var is now integer
$var += 2;

//var is now string
$var .= " is the total";

echo $var;
?>

The above code outputs "4.5 is the total".