RSS
 

Archive for the ‘PHP Lessons’ Category

PHP …Lesson Three

22 Apr

Hey
let’s Start

Variables in PHP
Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive, so $myvar is different from $myVar.

A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.
Example :

Image Hosting

PHP Superglobals
Superglobals are variables that available anywhere in the program code. They are :
$_SERVERVariables set by the web server or otherwise directly related to the execution environment of the current script. One useful variable is $_SERVER['REMOTE_ADDR'] which you can use to know you website visitor’s IP address
Image Hosting

Variable Scope
The scope of a variable is the context within which it is defined. Basically you can not access a variable which is defined in different scope.
The script below will not produce any output because the function Test() declares no $a variable. The echo statement looks for a local version of the $a variable, and it has not been assigned a value within this scope. Depending on error_reporting value in php.ini the script below will print nothing or issue an error message.
Image Hosting

Have a nice day

 
 

PHP ..Lesson Two

06 Apr

Now we will continue to Complete this PHP tutorial

Using Comments
Comment is a part of your PHP code that will not be translated by the PHP engine. You can use it to write documentation of your PHP script describing what the code should do. A comment can span only for one line or span multiple line.

Image Hosting

PHP support three kinds of comment tags :
1. //This is a one line comment
2. #This is a Unix shell-style comment. It’s also a one line comment
3. /* ….. */Use this multi line comment if you need to.

Have a nice day

 
 

Learn PHP language as Simple as

20 Mar

Hey Guys …

I am going to introduce you a great tutorial day by day to help you in PHP language .

as we all know . PHP is a dynamic Server side language used commonly to develop websites with databases and dynamic view . So this will help you building a good website that let you make money . beside PHP is a open Source Language . there is no fee to use it wherever , whenever.

Let’s Start
Lesson One : What is PHP ?
PHP is a web programming language used to write dynamic webpages. In this tutorial you will learn basics of PHP.

Opening & Ending PHP Tags
To open a block of PHP code in a page you can use one of these four sets of opening and closing tags
Image Hosting
Our First PHP Example

Image Hosting

Hello World, How Are You Today?

“; ?>

echo Statement
echo statement used to print whatever you want . you can embed any html tags on it .

NOTE : You have to enad any statment in PHP with semicolon (;)


Have a nice day

 
 

PHP lesson Seven

07 Dec

Using Functions

Real world applications are usually much larger than the examples above.
In has been proven that the best way to develop and maintain a large program
is to construct it from smaller pieces (functions) each of which is more
manageable
than the original program.

A function may be defined using syntax such as the following:

<?php

function addition($val1, $val2)

{

$sum = $val1 + $val2;

return $sum;

}

?>

Using Default Parameters

When calling a function you usually provide the same number of argument
as in the declaration. Like in the function above you usually call it like
this :

$result = addition(5, 10);

But you can actually call a function without providing all the arguments
by using default parameters.

<?php

function repeat($text, $num = 10)

{

echo “<ol>\r\n”;

for($i = 0; $i < $num; $i++)

{

echo “<li>$text </li>\r\n”;

}

echo “</ol>”;

}

// calling repeat with two arguments

repeat(“I’m the best”, 15);

// calling repeat with just one argument

repeat(“You’re the man”);

?>

Function repeat() have two arguments
$text
and $num. The $num
argument has a default value of 10. The first call to repeat()
will print the text 15 times because the value of $num
will be 15. But in the second call to repeat()
the second parameter is omitted so repeat() will
use the default $num value of 10 and so the text
is printed ten times.

Returning Values

Applications are usually a sequence of functions. The result from one function
is then passed to another function for processing and so on. Returning a value
from a function is done by using the return statement.

You can return any type from a function. An integer, double, array, object,
resource, etc.

Notice that in buildRows() I use the built
in function implode(). It joins all elements
of $array with the string ‘</td></tr><tr><td>
between each element. I also use the ‘.‘ (dot)
operator to concat the strings.

 
 

PHP lesson six

07 Dec

Control Structure

The next examples will show you how to use control structures in PHP. I won’t go through all just the ones that i will use in the code examples in this site. The control structures are

if
else
while
for

If Else
The if statement evaluates the truth value of it’s argument. If the argument evaluate as TRUE the code following the if statement will be executed. And if the argument evaluate as FALSE and there is an else statement then the code following the else statement will be executed.

Example : visitor- info.php
Source code : visitor-info.phps

The strpos() function returns the numeric position of the first occurrence of it’s second argument (‘Opera’) in the first argument ($agent). If the string ‘Opera’ is found inside $agent, the function returns the position of the string. Otherwise, it returns FALSE.

When you’re using Internet Explorer 6.0 on Windows XP the value of $_SERVER['HTTP_USER_AGENT'] would be something like:

Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)

and if you’re using Opera the value the value may look like this :

Mozilla/4.0 (compatible; MSIE 6.0; MSIE 5.5; Windows NT 5.1) Opera 7.0 [en]

So if i you use Opera the strpos() function will return value would be 61. Since 61 !== false then the first if statement will be evaluated as true and the value of $agent will be set to the string ‘Opera’.

Note that I use the !== to specify inequality instead of != The reason for this is because if the string is found in position 0 then the zero will be treated as FALSE, which is not the behaviour that I want.

While Loop
The while() statement is used to execute a piece of code repeatedly as long as the while expresssion evaluates as true. For example the code below will print the number one to nine.

Example : while.php
Source code : while.phps

‘;
$number += 1;
}
?>

You see that I make the code $number += 1; as bold. I did it simply to remind that even an experienced programmer can sometime forget that a loop will happily continue to run forever as long as the loop expression ( in this case $number < 10 ) evaluates as true. So when you're creating a loop please make sure you already put the code to make sure the loop will end in timely manner. Break The break statement is used to stop the execution of a loop. As an example the while loop below will stop when $number equals to 6. Example : break.php Source code : break.phps ';

if ($number == 6)
{
break;
}

$number += 1;
}
?>

You can stop the loop using the break statement. The break statement however will only stop the loop where it is declared. So if you have a cascading while loop and you put a break statement in the inner loop then only the inner loop execution that will be stopped.

Example : break2.php
Source code : break2.phps

“;

if ($room == 2)
{
break;
}

$room += 1;
}
$floor += 1;

echo “
“;
}
?>

If you run the example you will see that the outer loop, while ($floor <= 5), is executed five times and the inner loop only executed two times for each execution of the outer loop. This proof that the break statement only stop the execution of the inner loop where it's declared. For The for loop syntax in PHP is similar to C. For example to print 1 to 10 the for loop is like this }
?>

A more interesting function is to print this number in a table with alternating colors. Here is the code

Example : alternate-colors.php
Source : alternate-colors.phps



Alternating row colors

This code display different row colors depending on the value of $i. If $i is not divisible by two it prints yellow otherwise it prints gray colored rows.

 
 

PHP lesson five

07 Dec

Creating a string

To declare a string in PHP you can use double quotes ( ” ) or single
quotes ( ‘ ). There are some differences you need to know about using these
two.

If you’re using double-quoted strings variables will be expanded ( processed
). Special characters such as line feed ( \n ) and carriage return ( \r )
are expanded too. However, with single-quoted strings none of those thing
happen. Take a look at the example below to see what I mean.

Note that browsers don’t print newline characters ( \r and \n ) so when

a look at the source and you will see the effect of these newline characters.

<?php

$fruit = ‘jamblang’;

echo “My favourite fruit is $fruit <br>”;

echo ‘I lied, actually I hate $fruit <br>’;

echo “\r\n My first line \r\n and my second line <br>\r\n”;

echo ‘ Though I use \r\n this string is still on one line <br>’;

?>

String Concatenation

To concat two strings you need the dot ( . ) operator so in case you have
a long string and for the sake of readability you have to cut it into two
you can do it just like the example below.

Actually if you need to write a loong string and you want to write it to
multiple lines you don’t need concat the strings. You can do it just like
the second example below where $quote2 is split
into three lines.

<?php

$quote1 = “Never insult Dumbledore ” .

“in front
of me!”;

$quote2 = “Nami,

you are

my nakama!”;

echo $quote1 . “<br>”;

echo $quote2;

?>

String Functions

substr($string, $start, $end) : get a chunk
of $string

<?php

// print ‘12′

echo substr(‘123456789′, 0, 2);

// print ‘56789′

echo substr(‘123456789′, 4);

// print ‘89′

echo substr(‘123456789′, -2);

// print ‘456′

echo substr(‘123456789′, 3, -4);

?>

str_repeat($string, $n) : repeat $string $n
times

For example if you want to print a series of ten asteriks ( * ) you can
do it with a for loop like this :

<?php

for ($i = 0; $i < 10; $i++) {

echo ‘*’;

}

?>

Or you can go the easy way and do it like this :

<?php

echo str_repeat(‘*’, 10);

?>

strrchr($string, $char) : find the last occurence
of the character $char in $string

For example: you want to get the file extension from a file name. You can
use this function in conjunction with substr()

<?php

$ext = substr(strrchr($filename, ‘.’), 1);

?>

What the above code do is get a chunk of $filename
starting from the last dot in $filename
then get the substring of it starting from the second character ( index 1
).

To make things clearer suppose $filename is
‘tutorial.php’. Using strrchr(‘tutorial.php’,
‘.’)
yield ‘.php’ and after substr(‘.php’,
1)
we get the file extension; ‘php’

trim($string) : remove extra spaces at the
beginning and end of $string

<?php

// print ‘abc def’

echo trim(‘ abc def ‘);

?>

addslashes($string) : adding backslashes before
characters that need to be quoted in $string

This function is usually used on form values before being used for database
queries. You will see this function used a lot in this tutorial so there’s no need to present an example here.

explode($separator, $string) : Split $string
by $separator

This function is commonly used to extract values in a string which are separated
by a a certain separator string. For example, suppose we have some information
stored as comma separated values. To extract each values we ca do it like
shown below

<?php

// extract information from comma separated values

$csv = ‘Uzumaki Naruto,15,Konoha Village’;

$info = explode(‘,’, $csv);

?>

Now, $info is an array with three values :

Array

(

[0] => Uzumaki Naruto

[1] => 15

[2] => Konoha Village

)

We can further process this array like displaying them in a table, etc.

implode($string, $array) : Join the values
of $array using $string

This one do the opposite than the previous function. For example to reverse
back the $info array into a string we can do
it like this :

<?php

$info = array(‘Uzumaki Naruto’, 15, ‘Konoha Village’);

$csv = implode(‘,’, $info);

?>

Another example : Pretend we have an array containing some values and we
want to print them in an ordered list. We can use the implode()
like this :

<?php

// print ordered list of names in array

$names = array(‘Uchiha Sasuke’, ‘Haruno Sakura’, ‘Uzumaki Naruto’, ‘Kakashi’);

echo ‘<ol><li>’ . implode(‘</li><li>’, $names)
. ‘</li></ol>’;

?>

 
 

PHP…Lesson four

07 Dec

PHP supports eight primitive types.

Four scalar types:

  • boolean : expresses truth value, TRUE or FALSE. Any non zero values and
    non empty string are also counted as TRUE.
  • integer : round numbers (-5, 0, 123, 555, …)
  • float : floating-point number or ‘double’ (0.9283838, 23.0, …)
  • string : “Hello World”, ‘PHP and MySQL, etc

Two compound types:

  • array
  • object

And finally two special types:

  • resource ( one example is the return value of mysql_connect()
    function)
  • NULL

In PHP an array can have numeric key, associative key
or both. The value of an array can be of any type. To create an array use
the array() language construct like this.

Example :
Source code :

<?php

$numbers = array(1, 2, 3, 4, 5, 6);

$age = array(“mom” => 45, “pop” => 50, “bro”
=> 25);

$mixed = array(“hello” => “World”, 2 => “It’s
two”;

echo “numbers[4] = {$numbers[4]} <br>”;

echo “My mom’s age is {$age['mom']} <br>”;

echo “mixed['hello'] = {$mixed['hello']} <br>”;

echo “mixed[2] = {$mixed[2'}";

?>

When working with arrays there is one function I often used. The print_r()
function. Given an array this function will print the values in a format that
shows keys and elements

<?php

$myarray = array(1, 2, 3, 4, 5);

$myarray[5] = array(“Hi”, “Hello”, “Konnichiwa”,
“Apa Kabar”);

echo ‘<pre>’;

print_r($myarray);

echo ‘</pre>’;

?>

Don’t forget to print the preformatting tag <pre>
and </pre> before and after calling print_r().
If you don’t use them then you’ll have to view the page source to see a result
in correct format.

Type Juggling

In PHP you don’t need to explicitly specify a type for variables. A variable’s
type is determined by the context in which that variable is used. That is
to say, if you assign a string value to variable $var,
$var becomes a string. If you then assign an
integer value to $var, it becomes an integer.

An example of PHP’s automatic type conversion is the addition operator ‘+’.
If any of the operands is a float, then all operands are evaluated as floats,
and the result will be a float. Otherwise, the operands will be interpreted
as integers, and the result will also be an integer. Note that this does NOT
change the types of the operands themselves; the only change is in how the
operands are evaluated.

Example :

<?php

$myvar = “0″; // $myvar is string (ASCII 48)

$myvar += 2; // $myvar is now an integer (2)

$myvar = $foo + 1.3; // $myvar is now a float (3.3)

$myvar = 5 + “10 Piglets”; // $foo is integer (15)

?>

Type Casting

To cast a variable write the name of the desired type in parentheses before
the variable which is to be cast.

<?php

$abc = 10; // $abc is an integer

$xyz = (boolean) $abc; // $xyz is a boolean

echo “abc is $abc and xyz is $xyz <br>”;

?>

The casts allowed are:

  • (int), (integer) – cast to integer
  • (bool), (boolean) – cast to boolean
  • (float), (double), (real) – cast to float
  • (string) – cast to string
  • (array) – cast to array
  • (object) – cast to object