Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Ostp Unit 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 109

UNIT – 2

Overview of PHP Structure & Syntax


PHP
 Developed in 1995 by Rasmus Lerdorf (member of the Apache Group)
 originally designed as a tool for tracking visitors at Lerdorf's Website
 within 2 years, widely used in conjunction with the Apache Server
 developed into full-featured, scripting language for server-side
programming
 free, open-source
 server plug-ins exist for various servers
 now fully integrated to work with mySQL database
 PHP is similar to JavaScript, only it’s a Server-Side Language
 PHP code is embedded in HTML using tags
 when a page request arrives, the server recognizes PHP content via the
file extension (.php or .phtml)
 the server executes the PHP code, substitutes output into the HTML
page
 the resulting page is then downloaded to the client 2
 user never sees the PHP code, only the output in the page
WHAT DO YOU NEED?

 Our server supports PHP


 You don't need to do anything special! *
 You don't need to compile anything or install any extra
tools!
 Create some .php files in your web directory - and the
server will parse them for you.

* Slightly different rules apply when dealing with an


SQL database (as will be explained when we get to that
point).

3
 Most servers support PHP
 Download PHP for free here:
http://www.php.net/downloads.php
 Download MySQL for free here:
http://www.mysql.com/downloads/index.html
 Download Apache for free here:
http://httpd.apache.org/download.cgi

(Note: All of this is already present on the CS servers, so you


need not do any installation yourself to utilize PHP on our
machines.)
4
WHAT IS PHP?
 PHP == ‘Hypertext Preprocessor’
 Open-source, server-side scripting language

 Used to generate dynamic web-pages

 PHP scripts reside between reserved PHP tags


 This allows the programmer to embed PHP scripts within HTML
pages
 The acronym PHP means (in a slightly recursive definition)
 PHP: Hypertext Preprocessor

5
WHAT IS PHP (CONT’D)
 Interpreted language, scripts are parsed at run-time
rather than compiled beforehand
 Executed on the server-side

 Source-code not visible by client


 ‘View Source’ in browsers does not display the PHP code
 Various
built-in functions allow for fast development
 Compatible with many popular databases

6
WHAT DOES PHP CODE LOOK LIKE?

 Structurally similar to C/C++


 Supports procedural and object-oriented paradigm (to some
degree)
 All PHP statements end with a semi-colon

 Each PHP script must be enclosed in the reserved PHP tag

<?php

?>

7
HOW IT WORKS
 PHP code is usually embedded into HTML

 Processing the code :


1) The HTML code stands as it is

2) The PHP scripts are executed to create final HTML code

3) Both parts are combined and back

4) Resulting HTML is interpreted by a browser


8
ADVANTAGES OF PHP

 Freely available
 The PHP group provides complete source code free of
charge
 Similar syntax to C, Perl

 Works with many operating systems

 Can be deployed on many web servers

 Interacts with lots of databases

 It is supported by many providers of webhosting

9
HISTORY – INITIAL DEVELOPMENT
 Originally created by Rasmus Lerdorf
 PHP originally stood for Personal Home Page
 Replaces small set of Perl (Practical Extraction and Report
Language) scripts.
Perl is a general-purpose programming language originally
developed for text manipulation and now used for a wide
range of tasks including system administration, web
development, network programming, GUI development,
and more.
 Used as a tool for observing traffic on webpage

 PHP 2 (PHP/FI (Form Interpreter))


 First publicly released version (on June 8, 1995)
 Combination of Lerdorf’s Form Interpreter and original binary from
PHP
 Was able to communicate with databases
 Enabled the building of dynamical web application 10
 included Perl-like variables, form handling, and the ability to be
embedded HTML
HISTORY – RELEASED VERSIONS
 PHP 3
 The scripting core was rewritten by Zeev Suraski and Andi
Gutmans
 The name was changed to Hypertext Preprocessor
 It is able to work with MS Windows and Macintosh

 PHP4
 Added Zend engine. The Zend Engine is the open source
scripting engine that interprets the PHP programming
language.
 Introduced 'superglobals' ($_GET, $_POST, $_REQUEST, etc)

 None of these versions is under development now 11


 PHP 5
 It was published on May 1, 2008
 Uses enhanced Zend II engine

 It includes :

 support for object-oriented programming,

 the PHP Data Objects extension (simplifies accessing


databases)
 numerous performance enhancements

 PHP 5.5 on 2013-07-18


 PHP 5.6 on 2014-01-14
 PHP 7
 PHP 7 was released on December 3rd, 2015. It comes with a number
of new features, changes, and backwards compatibility breakages
that are outlined below.
 It gives very high performance, speed and provide many new
features compared to other versions.
 Latest versions of PHP are PHP 7.2.30, PHP 7.3.17, PHP 7.4.5 and 8.0.8 12
released on 1st July 2021.
PHPINFO()

 The phpinfo() function shows the php environment


 Use this to read system and server variables, setting stored
in php.ini, versions, and modules
 Notice that many of these data are in arrays

 phpinfo() is also a valuable debugging tool as it contains all


EGPCS (Environment, GET, POST, Cookie, Server) data.

 This is the first script you should write…


<?php
phpinfo();
13
?>
WEBSITES USING PHP

 According to W3Techs' data, PHP is used by 78.9% of all websites with


a known server-side programming language. So almost 8 out of every
10 websites that you visit on the Internet are using PHP in some way.

 Significant Examples
 Facebook
 Wikipedia
 Yahoo!
 MyYearbook
 Flickr
 Wordpress.com
 Tumblr
 Flipkart etc…. 14
CREATING BASIC PHP SCRIPTS
 Embedded language refers to code that is embedded within a
Web page (XHTML document)

 PHP code is typed directly into a Web page as


a separate section

 A Web page document containing PHP code must have an


extension of .php

 PHP code is never sent to a client’s Web browser


CREATING BASIC PHP SCRIPTS (CONTINUED)
 The Web page generated from the PHP code, and HTML or
XHTML elements found within the PHP file, is returned to
the client

 A PHP file that does not contain any PHP code should have
an .html extension

 .php is the default extension that most Web servers use to


process PHP scripts

16
CREATING PHP CODE BLOCKS
 Code declaration blocks are separate sections within a Web
page that are interpreted by the scripting engine

 There are four types of code declaration blocks:


 Standard PHP script delimiters
 The <script> element
 Short PHP script delimiters
 ASP-style script delimiters

17
STANDARD PHP SCRIPT DELIMITERS
 A delimiter is a character or sequence of characters used to
mark the beginning and end of a code segment

 The standard method of writing PHP code declaration


blocks is to use the <?php statements; ?> script delimiters

 The individual lines of code that make up a PHP script are


called statements

18
THE <SCRIPT> ELEMENT
 The <script> element identifies a script section in a Web page
document

 Assign a value of "php" to the language attribute of the


<script> element to identify the code block as PHP

<script type='text/javascript'>
function test()
{
alert("<?php echo "Testing"; ?>");
}
test();// to call the function
19
</script>
SHORT PHP SCRIPT DELIMITERS
 The syntax for the short PHP script delimiters is
<? statements; ?>
 Short delimiters can be disabled in a Web server’s
php.ini configuration file
 PHP scripts will not work if your Web site ISP does not
support short PHP script delimiters
 Short delimiters can be used in XHTML documents, but
not in XML documents
 Do following change in php.ini

short_open_tag=On 20
ASP-STYLE SCRIPT DELIMITERS
 The syntax for the ASP-style script delimiters is
<% statements; %>
 ASP-style script delimiters can be used in XHTML
documents, but not in XML documents
 ASP-style script delimiters can be enabled or disabled in the
php.ini configuration file
 To enable or disable ASP-style script delimiters, assign a
value of “On” or “Off ” to the asp_tags directive in the
php.ini configuration file

21
DISPLAYING SCRIPT RESULTS (CONTINUED)

PHP Diagnostic Information Web page 22


DISPLAYING SCRIPT RESULTS (CONTINUED)
 The echo() and print() statements are language constructs
of the PHP programming language
 A programming language construct refers to a built-in
feature of a programming language
 The echo() and print() statements are virtually identical
except:
 The print() statement returns a value of 1 if
it is successful
 It returns a value of 0 if it is not successful

23
DISPLAYING SCRIPT RESULTS (CONTINUED)
 Use the echo() and print() statements to return the results of
a PHP script within a Web page that is returned to a client

 A text string, or literal string, is text that is contained within


double or single quotation marks

 To pass multiple arguments to the echo() and print()


statements, separate them with commas like arguments
passed to a function

24
CREATING MULTIPLE CODE DECLARATION
BLOCKS
 For multiple script sections in a document, include a
separate code declaration block for each section
...
</head>
<body>
<h1>Multiple Script Sections</h1>
<h2>First Script Section</h2>
<?php echo “<p>Output from the first script section.</p>”;
?>
<h2>Second Script Section</h2>
<?php echo “<p>Output from the second script section.</p>”
;?>
</body>
</html>
25
CREATING MULTIPLE CODE DECLARATION
BLOCKS (CONTINUED)
 PHP code declaration blocks execute on a Web server before
a Web page is sent to a client
...
</head>
<body>
<h1>Multiple Script Sections</h1>
<h2>First Script Section</h2>
<p>Output from the first script section.</p>
<h2>Second Script Section</h2>
<p>Output from the second script section.</p>
</body>
</html>
26
CREATING MULTIPLE CODE DECLARATION
BLOCKS (CONTINUED)

output of a document with two PHP script sections


27
CASE SENSITIVITY IN PHP
 Programming language constructs in PHP are mostly
case insensitive

<?php
echo “<p>Explore <strong>Africa</strong>, <br />”;

Echo “<strong>South America</strong>, <br />”;

ECHO “ and <strong>Australia</strong>!</p>”;


?>

28
ADDING COMMENTS TO A PHP SCRIPT
 Comments are nonprinting lines placed in code such as:
 The name of the script
 Your name and the date you created the program
 Notes to yourself
 Instructions to future programmers who might need to
modify your work

29
ADDING COMMENTS TO A PHP SCRIPT
(CONTINUED)
 Line comments hide a single line of code
 Add // or # before the text
 Block comments hide multiple lines of code
 Add /* to the first line of code
 And */ after the last character in the code

 Standard C, C++, and shell comment symbols


// C++ and Java-style comment

# Shell-style comments
30
/* C-style comments
These can span multiple lines */
ADDING COMMENTS TO A PHP SCRIPT
(CONTINUED)
<?php
/*
This line is part of the block comment.
This line is also part of the block comment.
*/
echo “<h1>Comments Example</h1>”; // Line comments can follow code statements
// This line comment takes up an entire line.
# This is another way of creating a line comment.
/* This is another way of creating
a block comment. */
?>

31
USING VARIABLES AND CONSTANTS
 The values stored in computer memory are called
variables
 The name you assign to a variable is called an
identifier and it:
 Must begin with a dollar sign ($)
 Cannot begin with an underscore (_) or a number
 Cannot include spaces
 Is case sensitive

32
DECLARING AND INITIALIZING VARIABLES
 Specifying and creating a variable name is called
declaring the variable
 Assigning a first value to a variable is called
initializing the variable
 In PHP, you must declare and initialize a variable in
the same statement:
$variable_name = value;

33
DISPLAYING VARIABLES
 To print a variable with the echo() statement, pass the
variable name to the echo()
statement without enclosing it in quotation marks:
$VotingAge = 18;
Echo $VotingAge;
 To print both text strings and variables, send
them to the echo() statement as individual arguments,
separated by commas:
echo "<p>The legal voting age is ", $VotingAge, ".</p>";

34
DISPLAYING VARIABLES
 To print text strings and variables, you can send them to the
echo() statement as one argument enclosed in double
quotes:
echo "<p>The legal voting age is $VotingAge.</p>";
The legal voting age is 18.

 To print text strings and the variable name, you can send
them to the echo() statement as one argument enclosed in
single quotes:
echo ‘<p>The legal voting age is $VotingAge.</p>’;
The legal voting age is $VotingAge

35
MODIFYING VARIABLES
 You can modify a variable’s value at any point in a script
$SalesTotal = 40;
echo "<p>Your sales total is
$$SalesTotal</p>";
$SalesTotal = 50;
echo "<p>Your new sales total is
$$SalesTotal</p>";

36
WORKING WITH VARIABLES
 Settype($var, “integer”)
 allows you to set variable according to your wish
 Gettype()
 write the type of variable

 (.)
 Connects 2 variables of string type
 strlen()
 finds the length of a string
37
VARIABLES - SCOPE
 regular PHP variables have a single scope – the context
within the variable is defined (function, file etc.); the scope
include required and include files
ex.: $n=4;
include “vars.php”; //$n is visible in “vars.php”
 local variables from user-defined functions have a local
function scope:
$n=4;
function foo() { echo $n; } // $n is undefined here
 static variables – have a local function scope, but they exist
outside the function and keep their values between calls;
ex.: 38
function test() {
static $n = 0; $n++; echo $n; }
VARIABLES – GLOBAL SCOPE
 global variables declared within a function will refer to the
global version of those variables; ex.:
$a=2; $b=2;
function test() {
global $a, $b;
$c = $a + $b; //$c is here 4
}
 global variables can be accessed through the $GLOBALS
array:
$c = $GLOBALS[‘a’] + $GLOBALS[‘b’];
 the $GLOBALS array is an associative array with the name
of the global variable being the key and the contents of that
variable being the value of the array element; $GLOBALS
exists in any scope, this is because $GLOBALS is a 39

superglobal
VARIABLES – SUPERGLOBAL SCOPE
 superglobal variables are available in all scopes throughout the script; no need to be
declared global in a local function; were introduced in PHP 4
 the superglobal variables are:

$GLOBALS – contains references to all variables defined in the global scope of the
script
$_SERVER - array containing information such as headers, paths, and script locations;
built by the web server
$_GET - array of variables passed to the current script via the URL parameters
$_POST - array of variables passed to the current script via the HTTP POST method
$_FILES - array of items uploaded to the current script via the HTTP POST method
$_COOKIE - array of variables passed to the current script via HTTP Cookies
$_SESSION - array containing session variables available to the current script
$_REQUEST - array that by default contains the contents of $_GET, $_POST and
$_COOKIE
$_ENV - array of variables passed to the current script via the environment method40
 if the register_global directive is on, the variables from the superglobal arrays
become available in the global scope
VARIABLES (5) – GLOBAL VS. SUPERGLOBAL
EXAMPLES

function test_global()
{
// Most predefined variables aren't "super" and require
// 'global' to be available to the functions local scope.
global $HTTP_POST_VARS;

echo $HTTP_POST_VARS['name'];

// Superglobals are available in any scope and do


// not require 'global'. Superglobals are available
// as of PHP 4.1.0, and HTTP_POST_VARS is now
// deemed deprecated.
echo $_POST['name'];
} 41
$GLOBALS
function test() {
$foo = "local variable";

echo '$foo in global scope: ' . $GLOBALS["foo"] . "\n";


echo '$foo in current scope: ' . $foo . "\n";
}
$foo = "Example content";
test();

will print:
$foo in global scope: Example content
$foo in current scope: local variable 42
$_SERVER
 keys:
‘PHP_SELF’ – the filename currently executed
‘SERVER_ADDR’ – the IP address of the server
‘SERVER_PROTOCOL’ – name and version of the protocol via which the
page is requested; HTTP/1.1
‘REQUEST_METHOD’ – the request method
‘QUERY_STRING’ – the query string
‘DOCUMENT_ROOT’ – the document root under which the current script
is executed
‘REMOTE_ADDR’ – the client IP address
‘REMOTE_PORT’ – the client port
43
‘HTTP_ACCEPT’ – the HTTP accept field of the HTTP protocol
etc.
$_GET

 an html example
<form action="welcome.php" method="get">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
 after submit, the URL is:
http://www.w3schools.com/welcome.php?fname=Peter&age=37
 the ‘welcome.php’ file:
Welcome <?php echo $_GET["fname"]; ?>.<br />
You are <?php echo $_GET["age"]; ?> years old!
44
$_POST

 an html example
<form action="welcome.php" method=“post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
 after submit, the URL is:
http://www.w3schools.com/welcome.php
 the ‘welcome.php’ file:
Welcome <?php echo $_POST["fname"]; ?>.<br />
You are <?php echo $_POST["age"]; ?> years old!
45
DEFINING CONSTANTS
 A constant contains information that does not
change during the course of program execution
 Constant names do not begin with a dollar sign
 Constant names use all uppercase letters
 Use the define() function to create a constant
define("CONSTANT_NAME", value);
define("VOTING_AGE",18);
define("VOTING_AGE",18,TRUE);
 The value you pass to the define() function can be
a text string, number, or Boolean value

46
WORKING WITH DATA TYPES
 A data type is the specific category of information
that a variable contains
 Data types that can be assigned only a single value are
called primitive types

47
WORKING WITH DATA TYPES (CONTINUED)
 The PHP language supports:
 A resource data type – a special variable that holds a
reference to an external resource such
as a database or XML file
 Reference or composite data types, which contain
multiple values or complex types of information
 Two reference data types: arrays and objects

48
NUMERIC DATA TYPES
PHP supports two numeric data types:
 An integer is a positive or negative number with no
decimal places (-250, 2, 100, 10,000)
 A floating-point number is a number that contains
decimal places or that is written in exponential
notation (-6.16, 3.17, 2.7541)
 Exponential notation, or scientific notation, is short for
writing very large numbers or numbers with many
decimal places (2.0e11)

49
BOOLEAN VALUES
 A Boolean value is a value of true or false
 It decides which part of a program should execute
and which part should compare data
 In PHP programming, you can only use true or false

 In other programming languages, you can use


integers such as 1 = true, 0 = false

50
BUILDING EXPRESSIONS
 An expression is a literal value or variable that can
be evaluated by the PHP scripting engine to produce a
result
 Operands are variables and literals contained in an
expression
 A literal is a value such as a literal string or a number

 Operators are symbols (+) (*) that are used in


expressions to manipulate operands

51
BUILDING EXPRESSIONS (CONTINUED)

52
BUILDING EXPRESSIONS (CONTINUED)

 A binary operator requires an operand before and


after the operator
 $MyNumber = 100;

 A unary operator requires a single operand either


before or after the operator

53
ARITHMETIC OPERATORS
 Arithmetic operators are used in PHP to perform
mathematical calculations (+ - x ÷)

54
ARITHMETIC OPERATORS (CONTINUED)
$DivisionResult = 15 / 6;
$ModulusResult = 15 % 6;
echo "<p>15 divided by 6 is
$DivisionResult.</p>"; // prints '2.5'
echo "The whole number 6 goes into 15 twice, with a
remainder of $ModulusResult.</p>"; // prints '3'

55
Figure : Division and modulus expressions
ARITHMETIC UNARY OPERATORS
 The increment (++) and decrement (--) unary
operators can be used as prefix or postfix operators
 A prefix operator is placed before a variable

 A postfix operator is placed after a variable

56
ARITHMETIC UNARY OPERATORS (CONTINUED)

Script that uses the prefix increment operator

57
ARITHMETIC UNARY OPERATORS (CONTINUED)

Figure 1-25 Output of the prefix version of the student ID


script

58
Arithmetic Unary Operators (continued)

Script that uses the postfix increment operator


59
Arithmetic Unary Operators (continued)

Output of the postfix version of the student ID script

60
ASSIGNMENT OPERATORS
 Assignment operators are used for assigning
a value to a variable:
$MyFavoriteSuperHero = "Superman";
$MyFavoriteSuperHero = "Batman";
 Compound assignment operators perform
mathematical calculations on variables and literal
values in an expression, and then assign
a new value to the left operand

61
ASSIGNMENT OPERATORS (CONTINUED)

62
ASSIGNMENT OPERATORS
$x = 100;
$y = 200;
$x += $y;
echo $x;

$x = 10;
$y = 7;
$x -= $y;
echo $x;

63
COMPARISON AND CONDITIONAL OPERATORS
 Comparison operators are used to compare two operands
and determine how one operand compares to another
 A Boolean value of true or false is returned after two
operands are compared
 The comparison operator compares values, whereas the
assignment operator assigns values
 Comparison operators are used with conditional
statements and looping statements

64
COMPARISON AND CONDITIONAL OPERATORS
(CONTINUED)

65
COMPARISON AND CONDITIONAL OPERATORS
(CONTINUED)
 The conditional operator executes one of two
expressions, based on the results of a conditional
expression
 The syntax for the conditional operator is:
conditional expression ? expression1 :
expression2;
 If the conditional expression evaluates to true,
expression1 executes
 If the conditional expression evaluates to false,
expression2 executes

66
COMPARISON AND CONDITIONAL OPERATORS
(CONTINUED)
$BlackjackPlayer1 = 20;
($BlackjackPlayer1 <= 21) ? $Result =
"Player 1 is still in the game. " :
$Result =
"Player 1 is out of the action.";
echo "<p>", $Result, "</p>";

Output of a script with a conditional operator 67


LOGICAL OPERATORS
 Logical operators are used for comparing two Boolean
operands for equality
 A Boolean value of TRUE or FALSE is returned after two
operands are compared

68
LOGICAL OPERATORS
<?php
$TrueValue = true;
$FalseValue = false;
!$TrueValue ? $ReturnValue = "true" :
$ReturnValue = "false";
echo "<p>$ReturnValue<br />";
!$FalseValue ? $ReturnValue = "true" :
$ReturnValue = "false";
echo "$ReturnValue<br />";
$TrueValue || $FalseValue ? $ReturnValue = "true" :
$ReturnValue = "false";
echo "$ReturnValue<br />";
$TrueValue && $FalseValue ? $ReturnValue = "true" :
$ReturnValue = "false";
echo "$ReturnValue<br />";
?>
69
SPECIAL OPERATORS

70
TYPE CASTING
 Casting or type casting copies the value contained in
a variable of one data type into a variable of another
data type
 The PHP syntax for casting variables is:
$NewVariable = (new_type)
$OldVariable;
 (new_type) refers to the type-casting operator
representing the type to which you want to cast the
variable

71
GETTYPE()SETTYPE()FUNCTION
 gettype($var_name): Returns one of the following strings,
depending on the data type:
 Boolean
 Integer
 Double
 String
 Array
 Object
 Resource
 NULL
 Unknown type

 bool settype($var_name): it sets the new given datatype on


$var_name.

<?php
$a=5.2;
echo gettype($a);
echo "<br>";
settype($a,"int");
echo gettype($a); 72

?>
TYPE VALIDATION FUNCTIONS
 is_int() - Find whether the type of a variable is integer
 is_bool() - Finds out whether a variable is a boolean

 is_float() - Finds whether the type of a variable is float

 is_numeric() - Finds whether a variable is a number


or a numeric string
 is_string() - Find whether the type of a variable is
string
 is_array() - Finds whether a variable is an array

 is_object() - Finds whether a variable is an object

73
EXAMPLE
<?php
$values = array(23, "23", 23.5, "23.5", null, true, false);
foreach ($values as $value) {
echo "is_int(";
var_export($value);
echo ") = ";
var_dump(is_int($value));
}
?>
The above example will output:
is_int(23) = bool(true)
is_int('23') = bool(false)
is_int(23.5) = bool(false)
is_int('23.5') = bool(false)
is_int(NULL) = bool(false)
is_int(true) = bool(false)
is_int(false) = bool(false)
74
UNDERSTANDING OPERATOR PRECEDENCE
 Operator precedence refers to the order in which
operations in an expression are evaluated
 Associativity is the order in which operators of equal
precedence execute
 Associativity is evaluated on a left-to-right or a right-
to-left basis

75
UNDERSTANDING OPERATOR PRECEDENCE
(CONTINUED)

76
CONDITIONAL STATEMENTS
 If/ else
 After each statement stands (;)
 If more than one command should be executed, use curly
braces { }

 Switch / break
 Used for choosing one possibility from multiple cases
Switch ($var )
{
case : “x” : echo “good”;
break;
default : echo “wrong input” ; 77
}
LOOPS
 while - loops through a block of code as long as a
specified condition is true
 do...while - loops through a block of code once, and
then repeats the loop as long as a special condition is
true
 for - loops through a block of code a specified number
of times
 foreach -

78
THE WHILE STATEMENT
while (condition)
code to be executed;

<?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;
}
?> 79
THE DO...WHILE STATEMENT
do
{
code to be executed;
}
while (condition);

80
THE FOR STATEMENT
for (initialization; condition; increment)
{ code to be executed; }

<?php
for ($i=1; $i<=5; $i++)
{
echo "Hello World!<br />";
}
?>
81
THE FOREACH STATEMENT
<?php
$string = 'We have a string';
$array = explode(" ",$string);
foreach($array as $value)
echo $value . '<br />';
?>

82
BREAK AND CONTINUE
 break ends execution of the current for,
foreach while, do..while or switch structure.

 continue is used within looping structures to


skip the rest of the current loop iteration and
continue execution at the beginning of the
next iteration.

83
WHY FUNCTIONS?
 PHP has lots of built-in functions that we use all
the time
 We write out own functions when our code reaches
a certain level of complexity

84
TO FUNCTION OR NOT TO FUNCTION...
 Organize your code into “paragraphs” - capture a
complete thought and “name it”
 Don’t repeat yourself - make it work once and then
reuse it
 If something gets too long or complex, break up
logical chunks and put those chunks in functions
 Make a library of common stuff that you do over and
over - perhaps share this with your friends...

85
BUILT-IN FUNCTIONS...

 Much of the power of PHP comes from its built-in


functions
 Many modeled after C string library functions (i.e. strlen())

echo strrev(" .dlrow olleH");


echo str_repeat("Hip ", 2);
echo strtoupper("hooray!"); Hello world.
echo strlen("intro"); Hip Hip
echo "\n"; HOORAY!
5 86
DEFINING YOUR OWN FUNCTIONS

 We use the function keyword to define a function, we


name the function and take optional argument variables.
The body of the function is in a block of code { }

function greet() {
print "Hello\n";
} Hello
Hello
greet(); Hello
greet(); 87

greet();
CHOOSING FUNCTION NAMES
 Much like variable names - but do not start with a
dollar sign
 Start with a letter or underscore - consist of letters,
numbers, and underscores ( _ )
 Avoid built in function names
 Case does not matter – but please do not take
advantage of this

88
RETURN VALUES

 Often a function will take its arguments, do some


computation and return a value to be used as the value of
the function call in the calling expression. The return
keyword is used for this.

function greeting() {
return "Hello"; Hello Glenn
} Hello Sally
print greeting() . " Glenn\n"; 89
print greeting() . " Sally\n";
ARGUMENTS

 Functions can choose to accept optional arguments.


Within the function definition the variable names are
effectively "aliases" to the values passed in when the
function is called.

function howdy($lang) {
if ( $lang == 'es' ) return "Hello";
if ( $lang == 'fr' ) return “morning";
return "How are you?"; Hello john
} morning Rita

90
print howdy('es') . " john\n";
print howdy('fr') . " Rita\n";
OPTIONAL ARGUMENTS

 Arguments can have defaults and so can be omitted

function howdy($lang='es') {
if ( $lang == 'es' ) return "Hello";
if ( $lang == 'fr' ) return “morning";
return "Hello"; Hollo john
} morning Rita

print howdy() . " john\n";


print howdy('fr') . " Rita\n"; 91
CALL BY VALUE

 The argument variable within the function is an "alias" to


the actual variable
 But even further, the alias is to a *copy* of the actual
variable in the function call

function double($alias) {
$alias = $alias * 2;
return $alias; Value = 10 Doubled = 20
}
$val = 10;
92
$dval = double($val);
echo "Value = $val Doubled = $dval\n";
CALL BY REFERENCE

 Sometimes we want a function to change one of its


arguments - so we indicate that an argument is "by
reference" using ( & )

function triple(&$realthing) {
$realthing = $realthing * 3;
}

$val = 10;
triple($val);
93
echo "Triple = $val\n"; Triple = 30
PHP ARRAYS
WHAT IS AN ARRAY?
-An array can store one or more values in a
single variable name.

-Each element in the array is assigned its own


ID so that it can be easily accessed.
- $array[key] = value;

95
3 KINDS OF ARRAYS

1) Numeric Array
2) Associative Array
3) Multidimensional Array

96
NUMERIC ARRAY

- A numeric array stores each element with a


numeric ID key.

- 3 ways to write a numeric array.

97
AUTOMATICALLY

Example:

$names = array("Peter","Quagmire","Joe");

98
MUNUALLY
Example:

$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";

99
THE ID CAN BE USED IN A SCRIPT

Example:
<?php
$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";

echo $names[1] . " and " . $names[2] .


" are ". $names[0] . "'s neighbors";
?>
100
OUTPUT

Quagmire and Joe are Peter's neighbors

101
ASSOCIATIVE ARRAYS
-An associative array, each ID key is associated with a value.

-When storing data about specific named values, a numerical


array is not always the best way to do it.

-With associative arrays we can use the values as keys and


assign values to them.

102
EXAMPLE
Using an array to assign an age to a person.

$ages = array(”Brent"=>42, ”Andrew"=>25, "Joshua”=>16);

$ages[’Brent'] = ”42";
$ages[’Andrew'] = ”25";
$ages['Joshua'] = ”16";

103
THE ID CAN BE USED IN A SCRIPT
<?php
$ages[‘Brent’] = ”42";
$ages[‘Andrew’] = ”25";
$ages[‘Joshua’] = ”16";

echo Brent is " . $ages[‘Brent’] . " years old.";


?>

104
OUTPUT

-“Brent is 42 years old.”

105
MULTIDIMENSIONAL ARRAYS
- In a multidimensional array, each element in
the main array can also be an array.

- And each element in the sub-array can be an


array, and so on.

106
EXAMPLE
$families = array
(
"Griffin"=>array
(
"Peter",
"Lois",
"Megan" ),
"Quagmire"=>array ( "Glenn" ),
"Brown"=>array
(
"Cleveland",
"Loretta",
"Junior"
)
); 107
OUPUT
Array
(
[Griffin] => Array echo "Is " . $families['Griffin'][2] .
( " a part of the Griffin family?";
[0] => Peter
[1] => Lois
[2] => Megan
)
[Quagmire] => Array Is Megan a part of the Griffin family?
(
[0] => Glenn
)
[Brown] => Array
(
[0] => Cleveland
[1] => Loretta
[2] => Junior
)
108
)
END OF UNIT-2 : SUMMARY
 Background information of PHP History and Basics of
PHP
 Using variables, operators and expressions

 Conditional statements and iterations in PHP:


Conditional Statements: if statement, switch
statement.
 Looping: for loop, while loop, do…while statement,
for each statement.
 Functions and Arrays in PHP: PHP functions, creating
array.
 PHP image manipulation. 109

You might also like