Php Basic

40
Introduction to PHP Prepared By: Md. Sirajus Salayhin Assistant Programmer Nanosoft Email: [email protected] Web: http://nanoit.biz

Transcript of Php Basic

Page 1: Php Basic

Introduction to PHP

Prepared By: Md. Sirajus SalayhinAssistant Programmer

NanosoftEmail: [email protected]

Web: http://nanoit.biz

Page 2: Php Basic

What is it? and What do I need?

• What is PHP?– PHP: Hypertext Preprocessor– A server-side, cross-platform HTML

embedded scripting language

• What do I need?1. PHP-enabled web server2. Text editor3. A way to get PHP scripts from your

machine to the server

Page 3: Php Basic

Basic Syntax• Escaping from HTML

1. <?php … ?>2. <script language=“php”> … </script>3. <? … ?>4. <% … %>

• For Example… <?php

/* The world renowned first program. Programmer: Todd Barber

Date: October 31, 2006*/ echo “Hello World!”; #displays on the screen// A simple program to illustrate just the basics

?>

Page 4: Php Basic

Types• Boolean -> TRUE or FALSE• Integer – number of the set

Z = {..., -2, -1, 0, 1, 2, ...} • Float -> “decimal numbers”• String – series of characters

– Single quote (‘) – doesn’t expand variables– Double quote (“) – does expand variables

• Array – ordered map that assigns values to keys

• NULL – represents that a variable has no value. NULL is the only possible value.

See http://us2.php.net/manual/en/language.types.php for all possible types and more details.

Page 5: Php Basic

Variables

• Variables are represented by a dollar sign followed by the name of the variable.

• The variable name is case-sensitive. • Variable names follow the same rules as other labels

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

$this_is_a_valid_variable$this-one-is-not

Page 6: Php Basic

More Variables

• Predefined Variables– $GLOBALS – all variables currently in the global

scope– $_SERVER – all variables set by the web server– $_POST – variables provided by the HTTP POST– $_GET – variables provides by the HTTP GET (in

the URL)– $_SESSION – variables currently registered with

the script’s session

Page 7: Php Basic

More Variables - Scope• For the most part PHP variables have a single scope<?php $a=1;

include ‘header_info.php’;?>You can reference the $a variable in the file ‘header_info.php’

<?php$b=1;function footer_info () {

echo $b;}

footer_info();?>Nothing will output. The echo statement refers to the local scope of the variable (inside the function.) Global

variables must be declared global inside the function.

Page 8: Php Basic

More Variables – Scope• Global Keyword<?php

$a = 1;$b = 2;

function Sum(){ global $a, $b; $b = $a + $b;}

Sum();echo $b;

?>

What is $b?

• Passing Variables<?php

$a = 1;$b = 2;

function Sum ($a, $b){ $b = $a + $b;}

Sum($a, $b);echo $b;

?>

What is $b?

3 2

Page 9: Php Basic

More Variables - Variable• Variable names which can be set and used dynamically<?php

$a = ‘hello’;$$a = ‘world’;

echo “$a ${$a}”;echo “$a $hello”;

?>

• Constants - value cannot change during the execution of the script A constant is case-sensitive by default. By convention, constant identifiers are always uppercase.

<?phpdefine (“PI”,”3.14159265358979323846”);echo PI;

?>

This outputs

hello world hello world

This outputs3.14159265358979323846

Page 10: Php Basic

Operator PrecedenceAssociativity Operators Additional Information

non-associative new new

left [ array()

non-associative ++ -- increment/decrement

non-associative ~ - (int) (float) (string) (array) (object) @ types

non-associative instanceof types

right ! logical

left * / % arithmetic

left + - . arithmetic and string

left << >> bitwise

non-associative < <= > >= comparison

non-associative == != === !== comparison

left & bitwise and references

left ^ bitwise

left | bitwise

left && logical

left || logical

left ? : ternary

right = += -= *= /= .= %= &= |= ^= <<= >>= assignment

left and logical

left xor logical

left or logical

left , (comma) many uses

Page 11: Php Basic

Operators

• Arithmetic– -$a is negation– $a + $b is addition– $a - $b is subtraction– $a * $b is multiplication– $a / $b is division (always returns float)– $a % $b is modulus

• Assignment– $a = 5 is NOT “equal to.” It is “gets set to”– Combined operators

• +=, -=, *=, /=, %=, .=

Page 12: Php Basic

More Operators• Comparison

– $a == $b is equal– $a === $b is identical (includes type)– $a != $b is not equal– $a <> $b is not equal– $a !== $b is not identical– $a < $b is less than– $a > $b is greater than– $a <= $b is less than or equal to– $a >= $b is greater than or equal to

• Conditional– ?: is ternary – expr1 ? expr2 : expr3

• If expr1 is TRUE, the expression evaluates to expr2• If expr1 is FALSE, the expression evaluates to expr3

– Shorthand for single expression if statements

Page 13: Php Basic

Comparing Different TypesOperand 1 Operand

2Result

Null or String

String Convert NULL to “”, numerical or lexical comparison

Bool or null Anything Convert to bool, FALSE<TRUE

String or number (or resource)

String or number (or resource)

Translate strings (and resources) to numbers, usual math

Array Array Array with fewer numbers is smallerIf key from operand 1 is not found in operand 2 then arrays are incomparable Compare value by value

Array Anything Array is always greater

Page 14: Php Basic

More Operators• Error Control

– @ - suppresses any errors that may be generated• Works on expressions – if you can take a value of it then you can use it.

• Strings– Concatenation (.) – Concatenating Assignment (.=)

<$php@include “header_info.php”; // suppress error if file doesn’t exist

$a = “Hello”; // assign value Hello to $a$b = $a . “ World”; // $b evaluates to “Hello World”

$a .= “ World”; // $a evaluates to “Hello World”?>

Page 15: Php Basic

More Operators• Increment and Decrement

– ++$a – Preincrement – Increment by one, then return $a– $a++ - Postincrement – Return $a, then increment by one– --$a – Predecrement - Decrement by one, then return $a– $a-- - Postdecrement - Return $a, then decrement by one

<?php$a = 5;echo "Should be 5: " . $a++ . "<br />\n";echo "Should be 6: " . $a . "<br />\n";

$a = 5;echo "Should be 6: " . ++$a . "<br />\n";echo "Should be 6: " . $a . "<br />\n";

$a = 5;echo "Should be 5: " . $a-- . "<br />\n";echo "Should be 4: " . $a . "<br />\n";

$a = 5;echo "Should be 4: " . --$a . "<br />\n";echo "Should be 4: " . $a . "<br />\n";

?>

Page 16: Php Basic

More Operators

• Logical– $a and $b is AND – TRUE if both are TRUE– $a or $b is OR – TRUE if either is TRUE– $a xor $b is XOR – TRUE if either is TRUE, but not

both– ! $a is NOT – TRUE is $a is not TRUE– $a && $b is AND – TRUE if both are TRUE– $a || $b is OR – TRUE if either is TRUE

Page 17: Php Basic

More Operators

• Array– $a + $b is union – appends the right side to the left side

and doesn’t overwrite variables– $a == $b is Equal – TRUE is they have the same key/value

pairs– $a === $b is Identity – TRUE if they have the same

key/value pairs in the same order and of the same types– $a != $b is Inequality – TRUE if $a is not equal to $b– $a <> $b – Same as Inequality above– $a !== $b is Non-identity – TRUE if $a not identical to $b

Page 18: Php Basic

Array Comparisons<?php

$a = array ("a" => "apple", "b" => "banana");$b = array ("a" => "pear", "b" => "strawberry", "c" => "cherry");

$c = $a + $b; // Union of $a and $becho "Union of \$a and \$b: \n";var_dump ($c);

$c = $b + $a; // Union of $b and $aecho "Union of \$b and \$a: \n";var_dump ($c);

?>

<?php$a = array ("apple", "banana");$b = array (1 => "banana", "0" => "apple");

var_dump($a == $b); // bool(true)var_dump($a === $b); // bool(false)

?>

<?php$a = array(1,2,3);$b = array(1,7,8,9,10);$c = $a + $b; // Union of $a and $becho "Union of \$a and \$b: \n";//echo $cprint_r($c);

?>

Page 19: Php Basic

Control Structures -- if

• if – evaluates an expression to its Boolean value – if the expression evaluates to TRUE then the conditional code is executed; otherwise it is ignored

<?php$a = 5;if ($a = 6) echo “Hello World”;

?>

<?php$a = 5;if ($a == 6){ echo “Hello World”; $b = 7;}

?>

if block is executed anddisplays Hello World – note theassignment operator in the expression

if block is ignored andnothing is done – note the comparison operator in the expression

Page 20: Php Basic

Control Structures - else

• else – extension of if statement that executes code when the if expression evaluates to FALSE

<?php$a=3;$b=4;if ($a < $b) echo “Variable A is less than B”;else echo “Variable B is less than A”;

?>

Page 21: Php Basic

Control Structures - elseif

• elseif – another extension of if

<?php$a=3;$b=4;if ($a < $b) { echo “Variable A is less than B”;} elseif ($a == $b) { echo “Variable A has the same value as B”;} else { echo “Variable B is less than A”;}

?>

Page 22: Php Basic

Control Structures - while• while – execute the statements as long as the

expression evaluates to TRUE<?php

$a=3;while ($a==4){ echo “The value of a is ”.$a;}

?>

<?php$i = 1;while ($i <=10){ echo “i is set to “.$i++;}

?>

<?php $j = 0; while ($j <=10) { echo “j is set to “.++$j; }?>

Counts to

10Counts to

11

Page 23: Php Basic

Control Structures – do-while

• do-while – same as while except the code chunk is guaranteed to execute at least once

<?php$a=3;while ($a==4){ echo “The value of a is ”.$a;}

?>

<?php $a=3; do { echo “The value of a is ”.$a; } while ($a==4);?>

Evaluates to FALSE and whileloop statement(s) are neverexecuted

while expression isn’t evaluateduntil after at least one iteration of the do-while statements. Thisechoes “The value of a is 3” tothe screen.

Page 24: Php Basic

Control Structures - for• for (expr1; expr2; expr3)

{ statement(s); }– expr1 is evaluated unconditionally– expr2 is evaluated at the beginning of each

iteration; continues on TRUE– expr3 is evaluated at end of iteration

<?phpfor($i=1;$i<=10;$i++){ echo $i.”<br />”;}

?>

<?php $i=1; while ($i<=10) { echo $i.”<br />”; $i++; }?>

functions the same as

Page 25: Php Basic

Control Structures - switch• switch – the same as a series of if…elseif

statements<?php $i = 2; switch ($i) { case 0: echo $i; break; case 1: echo $i; break; case 2: echo $i; break; default: echo $i; break;?>

<?php $i=2; if ($i==0) echo $i; elseif ($i==1) echo $i; elseif ($i==2) echo $i;?>

Page 26: Php Basic

More switch

<?php $i = 4; switch ($i) { case 0: case 1: case 2: case 3: echo “I is less than 4”; break; case 4: echo “I is equal to 4”; break; default: echo “I is greater than 4”; break;?>

Combining cases Omitting Breaks

<?php $i = 4; switch ($i) { case 0: case 1: case 2: case 3: echo “I is less than 4”; case 4: echo “I is equal to 4”; default: echo “I is greater than 4”;?>

Page 27: Php Basic

Control Structures – require and include

• require – includes and evaluates a specific file; failure results in a Fatal Error

<?php require ‘header.php’;?>

• include - includes and evaluates a specific file; failure results in a Warning

<?php include ‘header.php’;?>

Page 28: Php Basic

Control Structures –require_once and include_once

• require_once – same as require except if the file has already been included, it will not be included again

<?php require_once ‘header.php’;?>

• include_once - same as include except if the file has already been included, it will not be included again

<?php include_once ‘header.php’;?>

• Use when the same file might be included and evaluated more than once during a particular execution of a script, and you want to be sure that it is included exactly once to avoid problems with function redefinitions, variable value reassignments, etc.

Page 29: Php Basic

User-defined functions

• Any valid PHP code can appear inside a function• Names follow the same rules as other labels in PHP• All functions in PHP have the global scope<?php function my_first_function ($arg1, $arg2, … ,$arg_n) //arguments aren’t mandatory { echo “PHP code goes here.”; return $return_value; //only used when something is returned }my_first_function(); // example of function call with no argumentsmy_first_function(1,2); // function with static argumentsmy_first_function($variable); // function with a variable as an argument}

Page 30: Php Basic

Functions and Arguments

• Information can be passed to the function by the argument list, a comma separated value list of expressions

• Arguments may be passed by:– Value (default)– Reference– Default argument list

• Variable-length argument lists are supported only in PHP4 and greater

Page 31: Php Basic

Function Examples• Passing by value examples<?php

######### NUMBERS ########### function add_numbers($value1, $value2) { echo “The numbers $value1 + $value2 equal “. $value1+$value2; }add_numbers(3,4); #adding 2 static numbersadd_numbers($age1,$age2); #adding 2 ages given by a user from a form

######### STRING ########### function display_instructions() { echo “Text goes here. Great for text that changes often and is used many places.”; }display_instructions();

######### ARRAYS ########### function add_array_values($func_array) { echo “The numbers $func_array[0] + $func_array[1] = “. $func_array[0] + $func_array[1]; }$main_program_array = array(2,3);add_array_values($array);?>

Page 32: Php Basic

More Function Examples• Passing by Reference and Default Argument List<?php$dbc = OCILogon("A201","$password","$database");function which_name($identifier,&$conn,$count="1"){

//global $dbc;//$conn =& $GLOBALS['dbc'];if ($identifier == "last") $sql = "select t100_first_name, t100_last_name from a201t100 where t100_last_name like 'Q%'";else $sql = "select t100_first_name, t100_last_name from a201t100 where t100_first_name like 'Q%'";$stmt = OCIParse($conn,$sql);OCIExecute($stmt);while ($row=OCI_fetch_row($stmt)) {

echo "<tr><td>".$count++."</td><td>$row[0] $row[1]</td></tr>";}OCIFreeStatement($stmt);OCILogoff($conn);}

echo "<table border='1' cellpadding='3’ width='30%'><tr><td>Count</td><td>Name</td></tr>\n“; which_name("first",$dbc);echo"</table>";?>

Page 33: Php Basic

More Function Examples

• Passing by reference notes– Used when you want to change the value of the object you

passed in– I don’t know of a realistic use except when using classes.

Can be used to return more than one value from a function (more on that later).

• Passing by default argument list– Any defaults must be on the right side of the argument list– Must be a constant expression– Uses default unless specified otherwise

Page 34: Php Basic

Variable length argument lists

• Uses the func_num_args(), func_get_arg(), and func_get_args() functions. <?phpfunction math(){ $numargs = func_num_args(); echo "Number of arguments: $numargs\n<br />"; echo "The second side is: " . func_get_arg(1) . "<br />\n"; $arg_list = func_get_args(); for ($i = 1; $i < $numargs +1; $i++) { echo "Side $i is: " . $arg_list[$i -1] . "<br />\n"; $area += $arg_list[$i -1]; } return $area;}

$area_of_object = math(3,4,5,6,1); // Prints 'Number of arguments: 5'echo "The area of the object is $area_of_object";?>

Page 35: Php Basic

Returning values

• A value can be returned by using the optional return() statement

• Function execution is ended immediately and control passed back to the line that called the function

• Returns a single variable– could be a single number or string– could be an array with several values

Page 36: Php Basic

return() examples

• Single number<?php function square($num) { return $num * $num; }echo square(5); //displays 25?>

• Single String<?php function display($string1, $string2=“World”) { return $string1 . $string2; }echo display(“Hello”,” Todd”);// displays Hello Toddecho display(“Hello ”);//displays Hello World?>

Page 37: Php Basic

More return() examples

• Array – use the built-in list() function to access the array elements

<?php function math($num1, $num2) { $div = $num1 / $num2; $mutli = $num1 * $num2; $add = $num1 + $num2; $sub = $num1 - $num2; return array($div, $mutli, $add, $sub); }list ($d, $m, $a, $s) = math("6","2");echo "Division: $d";echo "<br />Multiplication:". $m;echo "<br />Addition: $a";echo "<br />Subtraction: $s";?>

Page 38: Php Basic

More return() examples• Passing by reference to return multiple values<?php function split_string($input, $cut_point, &$first, &$second) { if(strlen($input) < $cut_point) return false; $first = substr($input, 0, $cut_point); $second = substr($input, $cut_point); return true; }$input_text = "abcdefghijklmnopqrstuvwxyz";if(split_string($input_text, 30, $first_half, $second_half) != true) { echo "Could not split input, cut-point is entire string!<br />";}if(split_string($input_text, 15, $first_half, $second_half) == true) { echo "First segment of input: $first_half<BR>"; echo "Second segment of input: $second_half<BR>";}?>

Page 39: Php Basic

Oh, by the way…• You can also return by reference. See

http://www.php.net/manual/en/language.references.return.php for a simple example and some explanation

• Remember variable variables? (Slide 9) PHP also allows for variable functions<?php function display() { echo “In a function…”; }$variable_function = “display”;$variable_function();?>

• Built in Functions - http://www.php.net/manual/en/funcref.php– Sessions - http://www.php.net/manual/en/ref.session.php– Oracle - http://www.php.net/manual/en/ref.oci8.php– Strings - http://www.php.net/manual/en/ref.strings.php– Date & Time - http://www.php.net/manual/en/ref.datetime.php– Arrays - http://www.php.net/manual/en/ref.array.php– File System - http://www.php.net/manual/en/ref.filesystem.php– PDF - http://www.php.net/manual/en/ref.filesystem.php

Page 40: Php Basic

Thank You …

Question ??