PHP Learn It! PHP Variables FAQ and Examples
Google

PHP Variables FAQ and Examples

How to define a float variable in PHP?

You define a float or a decimal variable just the way you define any variable in PHP.

<?php

$float_var = 3.5322322;
printf("%.1f", $float_var);

?>
Learn PHP and MySQL fast!

Learn how you can start building rich interactive database driven sites like a professional developer easily and quickly...

>> Order your copy now for just $39.95 <<

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.

<?php

$integer_var = 3;
echo $integer_var;

?>

How to concatenate variables in PHP?

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

<?php

$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.

<?php

$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.

<?php

$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.

<?php


$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.

<?php

$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...

<?php
//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".

From HTML to PHP programming...
Learn how to build websites in PHP

<< PHP Variables Top