Tuesday, December 14, 2010

PHP Tutorial Day3

Firstly apologies for keeping Day2 so small. I know it was a cake walk for you, but I was a bit busy and did not get chance to write more. Anyway, lets leave what happened in past and move onto todays work. Lets try to make up for yesterday's loss.

Functions

Syntax: some_function($var1, $var2,...,$varn)

Example:

print("some data"); is a function

abs($var1); is also a function.

<html>

<head>

<title></title>

</head>

<body>

<?php

$var1 = -10;

print (abs($var1));

?>

</body>

</html>

Result: 10

Although we passed negative value to the variable, yet it returned 10 value, reason being - abs() function is an absolute function. It returns absolute value without signs.

----------------------------------------------------------------------------------------

Defining a Function

function some_function($var1, $var2)

{

//some logic

}

On similar lines is returning the value from the function. Below mentioned example will show you how to define a function and how to return a value from a function.

Example:

<html>

<head>

<title></title>

</head>

<body>

<?php

$var1 = 10;

$var2 = 11;

function myfirstfunction($var1, $var2)

{

//addition

$var3 = $var1 + $var2;

print $var3;

}

myfirstfunction(10,20);

//function returning value

function mysecondfunction($var1,$var2)

{

$var3 = $var1 + $var2;

return $var3;

}

$var4 = mysecondfunction (20,40);

print "<br>".$var4;

?>

</body>

</html>

Result:

30

60

------------------------------------------------------------------------------

Variable Scope:

Scope of the variable remains confined to its function. Similarly, a variable declared outside the function will not be accessible within the function.

Global Variables:

These are variables which are available to everyone in every function i.e. also outside the function in which it has been defined.

Syntax: global $var1;

Static Variables:

These variables can maintain their state in the event of repeated calls to the same function.

<html>

<head>

<title></title>

</head>

<body>

<?php

$var1 = 10;

$var2 = 11;

print $var3;

//function returning value

function myfunc2($var1,$var2)

{

static $count01 = 1;

$var3 = $var1 + $var2;

print $count01++."<br>";

return $var3;

}

myfunc2(20,40);

myfunc2(10,40);

myfunc2(234,340);

?>

</body>

</html>

Result:

1

2

3

Function with an Optional Argument

Example:

function fontWrap( $txt, $size=3 )

{

//some statements

}

This function can work with 2 arguments supplied as well as just 1 argrument supplied.

i.e.

fontWrap("test data", 5); // in this case $size will assume value 5

OR

fontWrap("test data123"); // in this case $size will have the default value as 3.

CALL BY VALUE AND CALL BY REFERENCE

This is again standard thing.

Call by value is something which we have been doing in all our examples above.

Call by refrence has been shown with an example below:

<html>

<head>

<title></title>

</head>

<body>

<?php

//function returning value

function myfunc3($var1)

{

$var1++;

}

$var2 = 10;

myfunc3(&$var2);

print $var2;

?>

</body>

</html>

Result: 11

<html>

<head>

<title></title>

</head>

<body>

<?php

//function returning value

function myfunc3(&$var1)

{

$var1++;

}

$var2 = 121;

myfunc3($var2);

print $var2;

?>

</body>

</html>

Result: 122

------------------------------------------------------------------------------

TIP

You can also access global variables anywhere in your scripts with a built-in associative array called $GLOBALS. To access a global variable called $test within a function, you could reference it as $GLOBALS[test].

PHP Tutorial Day2

PHP Training by Swift Brains

More complex test expressions.

OR Operator

true || false true or false

This would always return TRUE. It means that any one operator is true then it returns TRUE.

AND Operator

true && false true and false

This would return false. If any any one operator is false then the returned value is FALSE.

Another example of operators:

( $x > 2 ) && ( $x < 15 )

Please note that $x is a variable here and we are testing if this variable is between 2 and 15 or not.

xor Operator

true xor true result is FALSE

! Not Operator

!true returns FALSE

--------------------------------------------------------------------------------------------------------------------------

Operators

Post Increment Operators

x = x + 1; is same as x +=1; and is also same as x++;

x++; is a post increment operator while ++x; is a pre-increment operator.

--------------------------------------------------------------------------------------------------------------------------

Order of Precedence for Selected Operators

top most is having highest precendence and lower most has lowest.

++ − − (cast)

/ *%

+−

< <= => >

== === !=

&&

||

66

= += − = /= *=%= .=

and

xor

or

--------------------------------------------------------------------------------------------------------------------------

Contants

define ("contant_name", 42);

This means that where ever we use constant_name it will automatically have the value 42

<html>

<head>

<title></title>

</head>

<body>

<?php

define ("SOME_CONSTANT",45);

print "This is a constant value ".SOME_CONSTANT;

?>

</body>

</html>

Some system defined constants

_FILE_; This returns the file name currently being read by the interpreter.

_LINE_; This returns the line number of the file being currently read by the interpreter.

PHP_VERSION; provides the PHP Version being used. This can be used to make the script run on a particular version only.

--------------------------------------------------------------------------------------------------------------------------

Controls and Loops

if Statement

if (expression)

{

some logic

}

if else Statement

if (expression)

{

some logic

}

else

{

some other logic

}

if else Statement

if (expression)

{

some logic

}

elseif

{

some other logic

}

else

{

some more other logic

}

Example:

<html>

<head>

<title></title>

</head>

<body>

<?php

$var1 = 10;

if ($var1 == 40)

{

print "This is a var1 value ".$var1;

}

elseif ($var1==10)

{

print "this is the value again ".$var1;

}

else

{

print "this is not the value";

}

?>

</body>

</html>

--------------------------------------------------------------------------------------------------------------------------

Switch Statement

switch (expression)

{

case result1:

//execute these statements if case1 is true

break;

case2 result2:

//execute these statements if case2 is true

break;

default:

//these statements are executed if none of the above conditions are true.

}

Caution Don't forget to include a break statement at the end of any code that will be executed as part of a case statement. Without break, the program flow will continue to the next case statement and ultimately to the default statement. In most cases, this will not be the behavior that you will be expecting.

Using the ? Operator

( expression )?returned_if_expression_is_true:returned_if_expression_is_false;

Example:

<html>

<head>

<title></title>

</head>

<body>

<?php

$var1 = 10;

print (($var1==10)?10:20);

?>

</body>

</html>

Result is 10

------------------------------------------------------------------------------------------------------------------------

Loops:

-----while loop-----------------------------------------------

while (expression)

{

//some statement

}

Example:

<html>

<head>

<title></title>

</head>

<body>

<?php

$var1 = 10;

while ($var1 < 20)

{

print ($var1)."<br>";

$var1++;

}

?>

</body>

</html>

----------do...while loop------------------------------------------

do {

// code to be executed

}

while (expression);

----------for statement------------------------------------------

for (variable assignment;variable expression;variable manipulation)

{

//code to be executed

}

Example:

<html>

<head>

<title></title>

</head>

<body>

<?php

$var1 = 10;

for ($var1 = 1; $var1<200;$var1++)

{

print ($var1)."<br>";

}

?>

</body>

</html>

Note: You can use break; statement to break out of loop at anytime.

--------------------------------------------------------------------------------------------------------------------------

Continue Statement:

To skip any computation you can use continue statement.

Example:

<html>

<head>

<title></title>

</head>

<body>

<?php

$var1 = 10;

for ($var1 = 1; $var1<200;$var1++)

{

if ($var1 < 10)

{

continue;

}

print ($var1)."<br>";

}

?>

</body>

</html>

ALL THE ABOVE MENTIONED LOOPS CAN BE USED IN NESTED FORMAT. SINCE AT THE VERY BEGINNING OF THE TUTORIAL I ASSUMED THAT THE READEER IS HAVING ACQUIANTANCE WITH ATLEAST ONE PROGRAMMING STATEMENT SO I AM NOT GOING TO EXPLAIN NESTED LOOPS HERE.

--------------------------------------------------------------------------------------------------------------------------

--------------------------------------------------------------------------------------------------------------------------

--------------------------------------------------------------------------------------------------------------------------

Sunday, December 12, 2010

PHP Tutorial Day1

This is not going to be a tutorial which is going to explain in much detail about each and everything about PHP. My main aim is to make a tutorial which is easy to understand for someone who has experience with any of the programming language and now wants to get into the beautiful world of PHP.

PHP training by Swift Brains.

Installing the system to get PHP moving.

Windows:

Download WAMP and install it on your windows machine. It will install Apache webserver, MySQL, and PHP and would configure it such a way that all of them work together. Typical installation creates a www folder in C Drive.

Linux:

Download XAMPP and install it on your Linux machine.(I am assuming that you know how to install applications on Linux). This is also on the same lines as WAMP.

These tools are more so easy to use, yet if you feel any problem please feel free to contact me.

As an IDE (Integrated Development Environment) you can use Netbeans for PHP or anything you wish.

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Lets start on with actual tutorial.

First PHP Script

<?PHP print("Hello World!!") ?>

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

PHP Tag Starts and ends with either

<?PHP and ?> This is the best way to code

OR

<? and ?> Not recommended as you will have to tweak your php.ini file to get this working. This type of code is known as PHP short Tags. Tweak php.ini to set short_open_tag = On

OR

<% and %> ASP Style tags. Again you need to tweak php.ini to get this working. Tweak php.ini to set asp_tags = On;

OR

<SCRIPT LANGUAGE="PHP"> and </SCRIPT> you can also use this.

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

PHP Script including HTML

Create a file, say, helloworld.php and put the below mentioned code in it. Place this file at appropriate place to run and then open your browser http://localhost/helloworld.php

<html>

<head>

<title> PHP Tutorial by Swift Brains </title>

</head>

<body>

<?php Print ("hello world"); ?>

</body>

</html>

PLEASE NOTE THAT A PHP STATEMENT ENDS WITH A SEMI COLON ";". IF YOU WILL NOT PUT IT THEN IT WON'T FUNCTION.

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

How to add comments to PHP code

Single Line comments have // or # as the start

Multiple line comments are between /* and */

Examples:

// this is a comment

# this is another comment

/*

this is a comment

and its not read by PHP Interpreter

*

/

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Variables in PHP

Variables are container which can hold value.

Variables in PHP start with $ sign. Example: $variable1

Variables can contain numbers, letters, and underscore

Declaring PHP variable

Usually PHP Variables are declared and assigned value in the same statement

$var1 = 8

$var2 = 16

This means that if you write

<?php print 8; ?>

or

<?php print $var1; ?>

both would yield same result.

Dynamic Variables

PHP has a brilliant and at the same time quite confusing concept of Dynamic Variables.

$var1 = "value1";

this is same as

$holder = "var1";

$$holder = "value1";

The $holder variable contains the string "value1", so you can think of $$holder as a dollar sign followed by the value of $holder. PHP interprets this as $var1.

(Make it a habit to put semi colons are statement completion else you would not be able to get anything working)

Syntax to acess Dynamic Variables is exactly same.

As per above example

<?php print $var1; ?>

will print value1

but

<?php print $$holder; ?>

will not print value1 as a result, instead it will print $var1

Try with

<html>

<head>

<title></title>

</head>

<body>

<?php

$var1 = "value1";

$holder = "var1";

Print ("$var1");

?>

</body>

</html>

AND

<html>

<head>

<title></title>

</head>

<body>

<?php

$var1 = "value1";

$holder = "var1";

Print ("$$holder");

?>

</body>

</html>

Inorder to get value1 as the output for the second code also you need to write it this way

Print ("${$holder}") ;

Example Code:

<html>

<head>

<title></title>

</head>

<body>

<?php

$var1 = "value1";

$holder = "var1";

Print ("${$holder}") ;

?>

</body>

</html>

References to Variables

By Value

You can provide reference to variables too.

$var1 = $var2;

This means that if $var2 had value 10 then after this statement $var1 will contain the value 10.

Now even if we change the value of $var2 to 20 still $var1 will contain the same old value 10.

By reference

this is done by use of & sign as shown in statement below.

$var1 = &$var2

Now if we change the value of any of them, the value of both the variables will change because right now both are accessing the same memoery location. This is same concept as in C pointer.

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Data Types

Integer - 5

Double - 1.234

String - "hello world"

Boolean - true

Object - Discussed later

Array - discussed later

You can use PHP's inbuilt function gettype() to test the type of any variable. If you place a variable between the parentheses of the function call, gettype() returns a string representing the relevant type.

Example:

<html>

<head>

<title></title>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

</head>

<body>

<?php

$var1 = "value1";

$var2 = 5;

print gettype($var1);

print gettype($var2);

?>

</body>

</html>

Returns

StringInteger i.e. var1 is string type and var2 is integer type.

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Changing Variable Types

We can use settype() function to change the type of a variable.

<html>

<head>

<title></title>

</head>

<body>

<?php

$var1 = "value1";

$var2 = 5;

settype($var2, string);

print gettype($var1);

print "<br>";

print gettype($var2);

?>

</body>

</html>

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Type Casting

$var1 = (double) $var2;

This makes the var1 type as double.

<html>

<head>

<title></title>

</head>

<body>

<?php

$var1 = "value1";

$var2 = 5;

settype($var1, integer);

$var2 = (double)$var1;

print gettype($var1);

print "<br>";

print gettype($var2);

?>

</body>

</html>

This would print

integer

double

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Operators and Expressions

Asignment Operator

$var1 = "value1";

print ($var1);

This results in value1

(I hope by now you are a little easy with programming in PHP so I am not writing the complete code everytime)

You can also do assignment as

print ($var1 = "value1");

This results in value1

Arithmetic Operators

+, -, *, /, %

% is a mod operator and gives output as the remainder. Example 10%3 gives result as 1.

Concatenation Operators

"hello"."world"

gives value as helloworld.

Regardless of datatype of the operands, they are treated as strings and the result is always a string.

Other Assignment Operators

$x = 4;

$x += 4; // $x now equals 8

is equivalent to

$x = 4;

$x = $x + 4; // $x now equals 8

So options are

+=

*=

-=

/=

%=

.=

Comparison Operators

== equivalance, left is equivalent to right

!= non equivalence, left is not equivalent right

=== identical, left is equivalent to right and both are of same type

> greater than

>= greater than equal to

< less than

<= less than equal to