Variables

Variables are used to store data (String, Numbers, etc..) in a program.



In PHP, variables start with symbol $. Examples for variable name

PHP Code:
$name
$companyName 
It is always better to use descriptive name for variables, so you know what is stored in a variable. For example, to store mark, we use variable $mark

PHP Code:
$mark 100// Good
$m1 100// Bad, it will work but $m1, how we know what is stored in it ? It can be anything. 
In above example, we stored numeric value in variable. When storing numeric value, we don't use quotes.

Lets have some string variable

PHP Code:
$name 'Batman';
$companyName 'FlashWebHost.com'
Now lets have some real PHP examples

day_2_variables_1.php

PHP Code:
<?php

$companyName 
'FlashWebHost.com';

echo  
$companyName;
Now lets make it little more friendly with PHP string concatenation, that is joining two strings.

day_2_variables_2.php

PHP Code:
<?php

$companyName 
'FlashWebHost.com';

echo  
'Welcome to ' $companyName;
day_2_variables_3.php

Another example with string and numeric variables.

PHP Code:
<?php

$name 
'Raju';
$rank 1;
$mark 1000;
$school 'LP School';

echo  
$name ' from ' $school ' got rank ' $rank '. He have ' $mark ' marks.';

Back to School, some simple maths

Here are some basic numeric operations using PHP

day_2_variables_4.php

PHP Code:
<?php

$numCats 
10;
$numDogs 20;

echo 
'Total number of animals ' . ($numCats $numDogs);
day_2_variables_5.php

In this example we use multiplication operator in PHP to multiply 2 numbers.

PHP Code:
<?php

$costOfApple 
12.00;
$numApple 8;

echo 
'Cost of ' $numApple ' apples = Rs: ' . ($numApple $costOfApple) . '/-';
day_2_variables_6.php

Lets do some billing.

PHP Code:
<?php

$webhosting_price 
399;
$domain_price 500;
$discount 0.1// 10% discount.

echo 'Total cost = Rs: ' . ($webhosting_price $domain_price) . '/-';
echo 
'<br>';echo 'Price After discount = Rs: ' . ( ($webhosting_price $domain_price) -  (($webhosting_price $domain_price) *  $discount)) . '/-';
That is lot of brackets, and repeated maths operation ($webhosting_price + $domain_price repeated 3 times), that is not efficient, lets simplify the code.

day_2_variables_7.php

Following code do exactly same as day_2_variables_6.php, but we added extra variable $total_cost, that store the value of $webhosting_price + $domain_price.

PHP Code:
<?php

$webhosting_price 
399;
$domain_price 500;
$discount 0.1// 10% discount.
$total_cost $webhosting_price $domain_price;

echo 
'Total cost = Rs: ' $total_cost '/-';echo '<br>';
echo 
'Price After discount = Rs: ' . ( $total_cost -  ($total_cost *  $discount)) . '/-';