Variables in PHP
Variables are used for storing a values, like text strings, numbers or arrays.
When a variable is set it can be used over and over again in your script
All variables in PHP start with a $ sign symbol.
The correct way of setting a variable in PHP:$var_name = value;
Let's try creating a variable with a string, and a variable with a number:
PHP Code:
<?php
$txt = "Hello World!";
$number = 16;
?>
Displaying variable in php is very easy. Here is an example ---
PHP Code:
PHP Code:
<?php
$txt = "Hello World!";
$number = 16;
echo $txt;
echo $number;
?>
Result:
Displaying variables with string in php is also very easy. Here is an example ---
PHP Code:
<?php
$txt = "Hello World!";
$number = 16;
echo "$txt is text<br>$number is Number";
?>
Result:
Quote:
Hello World! is text
16 is Number
|
You can use PHP and HTML together. For this you just use <? and ?> tag within those you will write your php code. But your page extention must be .php. Let's try the following example --
PHP Code:
<html>
<head><title>Test page with php+html</title></head>
<body>
<?php
echo "Welcome to test page";
?>
</body>
</html>
If..Else is a common condition function for php.
Structure of If..Else ( Single Condition )
Code:
Quote:
if(condition)
statement1;
else
statement2;
|
Example ( Single Condition )
PHP Code:
Code:
if($i==1)
$i=$i+1;
else
$i=$i-1;
Structure of If..Else ( Multiple Condition )
i
Quote:
f(condition){
statement1;
..
...
statementn;
}
else{
statement1;
..
...
statementn;
}
|
Example ( Multiple Condition )
PHP Code:
if($i==1){
$i=$i+1;
$j=2;
}
else{
$i=$i-1;
$j=3;
}
For Loop is the mostly used loop function not only php but also any other language.
Structure of FOR LOOP:
Code:
Quote:
for(initialization; condition; increment/decrement)
{
statement1;
..
...
....
statementn;
}
|
Example of FOR LOOP:
PHP Code:
for($i=1; $i<=10; $i++)
{
$a=$a+1;
$n=$n+1;
}
While loop in PHP:
==================
Structure:
=========
Quote:
intialization;
while(condition){
statement1;
statement2;
.
.
.
statementN;
loop factor;
}
|
Example:
=========
PHP Code:
$i=0;
while($i<=10){
echo "$i ";
$i=$i+1;
}
Result:
=========
Redirecting in PHP:
===============
Redirecting to any url from a php page is very easy task. Just a bit of use of a function is needed. Let's do it.
The following code will redirect user to the url
"http://fahimgallery.freehostia.com"
Code:
<?
header('Location: http://fahimgallery.freehostia.com/');
?>
Note
Quote:
|
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.
|
Adding value of two variables in PHP
============================
Code:
<?
$a=1;
$b=2;
$c=$a+$b;
echo $c;
?>
Result:
============================
Concating Variables in PHP:
=======================
Concating variables in PHP needs just a
dot(.) between two variables
Code:
Code:
<?
$var1='Hello';
$var2=' ';
$var3='World';
$final=$var1.$var2.$var3;
echo $final;
?>
Result:
Source: iGuides.org Webmasters Talk