0% found this document useful (0 votes)
60 views29 pages

Chapter 2

Uploaded by

Dawit Sebhat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views29 pages

Chapter 2

Uploaded by

Dawit Sebhat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Chapter 2 - Server Side Scripting Basics (php)

Introduction
Today’s Web users expect exciting pages that are updated frequently and provide a customized experience. For them, Web sites are more like
communities, to which they’ll return time and again. At the same time, Web-site administrators want sites that are easier to update and maintain,
understanding that’s the only reasonable way to keep up with visitors’ expectations. For these reasons and more, PHP and MySQL have become
the de facto standards for creating dynamic, database driven Web sites.

What Are Dynamic Web Sites?

Dynamic Web sites are flexible and potent creatures, more accurately described as applications than merely sites. DynamicWeb sites

 Respond to different parameters (for example, the time of day or the version of the visitor’s Web browser)
 Have a “memory,” allowing for user registration and login, e-commerce, and similar processes
 Almost always integrate HTML forms, allowing visitors to perform searches, provide feedback, and so forth
 Often have interfaces where administrators can manage the site’s content
 Are easier to maintain, upgrade, and build upon than statically made sites

There are many technologies available for creating dynamic Web sites. The most common are ASP.NET (Active Server Pages, a Microsoft
construct), JSP (Java Server Pages), ColdFusion, Ruby on Rails (a Web development framework for the Ruby programming language), and PHP.
Dynamic Web sites don’t always rely on a database, but more and more of them do, particularly as excellent database applications like MySQL are
available at little to no cost.

What is PHP?

PHP originally stood for “Personal Home Page” as it was created in 1994 by Rasmus Lerdorf to track the visitors to his online résumé. As its
usefulness and capabilities grew (and as it started being used in more professional situations), it came to mean “PHP: Hypertext Preprocessor.”
According to the official PHP Web site, found at www.php.net A, PHP is a “widely used general-purpose scripting language that is especially
suited for Web development and can be embedded into HTML.”

1
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
PHP is a server-side, cross-platform technology, both descriptions being important. Server side refers to the fact that everything PHP does occurs
on the server. A Web server application, like Apache or Microsoft’s IIS (Internet Information Services), is required and all PHP scripts must be
accessed through a URL (http://something). Its cross-platform nature means that PHP runs on most operating systems, including Windows, UNIX
(and its many variants), and Macintosh. More important, the PHP scripts written on one server will normally work on another with little or no
modification.

PHP has seen an exponential growth in use since its inception, and is the server-side technology of choice on over 76 percent of all Web sites. In
terms of all programming languages, PHP is the fifth most popular after Java, C, C++ and C#.

How pHp works?

As previously stated, PHP is a server-side language. This means that the code you write in PHP sits on a host computer called a server. The server
sends Web pages to the requesting visitors (you, the client, with your Web browser).When a visitor goes to a Web site written in PHP, the server
reads the PHP code and then processes it according to its scripted directions. In the example shown in below, the PHP code tells the server to send
the appropriate data—HTML code—to the Web browser, which treats the received code as it would a standard HTML page. This differs from a
static HTML site where, when a request is made, the server merely sends the HTML data to the Web browser and there is no server-side
interpretation occurring. Because no server-side action is required, you can run HTML pages in your Web browser without using a server at all. To
the end user and the Web browser there is no perceptible difference between what home.html and home.php may look like, but how that page’s
content was created will be significantly different.

2
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
What is MySQL?

MySQL (www.mysql.com) is the world’s most popular open-source database. In fact, today MySQL is a viable competitor to the pricey goliaths
such as Oracle and Microsoft’s SQL Server (and, ironically, MySQL is owned by Oracle). Like PHP, MySQL offers excellent performance,
portability, and reliability, with a moderate learning curve and little to no cost.

MySQL is a database management system (DBMS) for relational databases (therefore, MySQL is an RDBMS). A database, in the simplest terms,
is a collection of data, be it text, numbers, or binary files, stored and kept organized by the DBMS.

By incorporating a database into a Web application, some of the data generated by PHP can be retrieved from MySQL . This further moves the
site’s content from a static (hard-coded) basis to a flexible one, flexibility being the key to a dynamic Web site.

3
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
MySQL has been known to handle databases as large as 60,000 tables with more than 5 billion rows. MySQL can work with tables as large as 8
million terabytes on some operating systems, generally a healthy 4 GB otherwise. MySQL is used by NASA and the United States Census Bureau,
among many others.

Basic Syntax in PHP

PHP is an HTML-embedded scripting language, meaning that you can intermingle PHP and HTML code within the same file. So to begin
programming with PHP, start with a simple Web page. Script 1.1 is an example of a no-frills, no-content XHTML Transitional document, which
will be used as the foundation for most Web pages. Please also note that the template uses UTF-8 encoding, a topic discussed in the sidebar. To
add PHP code to a page, place it with in PHP tags:

<?php

?>

Anything written within these tags will be treated by the Web

server as PHP, meaning the PHP interpreter will process the

code. Any text outside of the PHP tags is immediately sent to

the Web browser as regular HTML. (Because PHP is most often

used to create content displayed in the Web browser, the PHP tags are normally put somewhere within the page’s body.)

4
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
Along with placing PHP code within PHP tags, your PHP files must have a proper extension. The extension tells the server to treat the script in a
special way, namely, as a PHP page. Most Web servers use .html for standard HTML pages and .php for PHP files.

To make a basic pHpscript:

1. Create a new document in your text editor or IDE, to be named first.php


2. Create a basic HTML document
3. Before the closing bodytag, insert the PHP tags:
<?php
?>
4. Save the file as first.php.
5. Place the file in the proper directory of your Web server (localhost, webserver or IIS).
6. Run first.php in your Web browser (access them via a URL e.g. localhost/first.php).

Sending Data to the Web Browser

To create dynamic website with PHP, you must know how to send data to the Web browser. PHP has a number of built-in functions for this
purpose, the most common being echo and print. I personally tend to favor echo: You could use print instead, if you prefer (the name more
obviously indicates what it does):

echo 'Hello, world!'; print 'Hello, world!';

echo "What's new?"; print "What's new?";

What can PHP do?

 PHP can generate dynamic page content


 PHP can create, open, read, write, and close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your database
 PHP can restrict users to access some pages on your website
 PHP can encrypt data

5
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
With PHP we are not limited to output HTML. We can output images, PDF files, and even flash movies. We can also output any text, such as
XHTML and XML.

Why PHP?

 PHP runs on different platforms (Windows, Linux, UNIX, Mac OSX, etc.)
 PHP is compatible with almost all servers used today (Apache,IIS, etc.)
 PHP has support for a wide range of databases
 PHP is free. Download it from the official PHP resource: www.php.net
 PHP is easy to learn and runs efficiently on the server side

Writing Comments in PHP

<! DOCTYPE html> PHP Variables


<html> Variables are "containers" for storing information:
<body> Example

<?php <?php

//This is a PHP comment line $x=5;

/* $y=6;

This is a PHP comment $z=$x+$y;

block echo $z;

*/ ?>

?> Much Like Algebra x=5, y=6, z=x+y

</body> In algebra we use letters (like x) to hold values (like 5).

</html> From the expression z=x+y above, we can calculate the value of z to be 11

6
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
Rules for PHP variables:

 A variable starts with the $ sign, followed by the name of the variable
 A variable name must begin with a letter or the underscore character
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
 A variable name should not contain spaces Variable names are case sensitive ($y and $Y are two different variables)

Both PHP statements and PHP variables are case-sensitive.

Creating (Declaring) PHP Variables

PHP has no command for declaring a variable. A variable is created the moment you first assign a value to it:

$txt="Hello world!"; or $x=5;

After the execution of the statements above, the variable txt will hold the value Hello world!, and the variable x will hold the value 5.

Note: When we assign a text value to a variable, put quotes around the value.

PHP is a Loosely Typed Language

In the example above, notice that we did not have to tell PHP which data type the variable is. PHP automatically converts the variable to the
correct data type, depending on its value. In a strongly typed programming language, we will have to declare (define) the type and name of the
variable before using it.

PHP Variable Scopes

The scope of a variable is the part of the script where the variable can be referenced/used.

PHP has four different variable scopes:

1. Local
2. global
3. static
4. parameter
1. Local Scope

7
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
A variable declared within a PHP function is local and can only be accessed within that function:

Example

<?php The script above will not produce any output because the echo statement refers to the
local scope variable $x, which has not been assigned a value within this scope.
$x=5; // global scope
We can have local variables with the same name in different functions, because local
function myTest()
variables are only recognized by the function in which they are declared.
{
Local variables are deleted as soon as the function is completed.
echo $x; // local scope

myTest();

?>

2. Global Scope

A variable that is defined outside of any function, has a global scope. Global variables can be accessed from any part of the script, EXCEPT from
within a function.

To access a global variable from within a function, use the global keyword:

Example PHP also stores all global variables in an array called $GLOBALS[index].

<?php The index holds the name of the variable. This array is also accessible from
within functions and can be used to update global variables directly.
$x=5; // global scope
The example above can be rewritten like this:
$y=10; // global scope
<?php
function myTest()
$x=5;

$y=10;
8
function
By: Berihun. M (Lecturer (MSc IT), myTest()
(BSc CS))

{
{

global $x,$y;

$y=$x+$y;

myTest();

echo $y; // outputs 15

?> ** Note: how global key word is used.

3. Static Scope

When a function is completed, all of its variables are normally deleted. However, sometimes you want a local variable to not be deleted. To do
this, use the static keyword when you first declare the variable:
Then, each time the function is called, that variable will still have the information it
Example
contained from the last time the function was called.
<?php
Note: The variable is still local to the function.
function myTest()
4. Parameter Scope
{
A parameter is a local variable whose value is passed to the function by the calling code.
static $x=0;
Parameters are declared in a parameter list as part of the function declaration:
echo $x;
<?php
$x++;
function myTest($x) * Note: Parameters are also called arguments
}
{
myTest();
echo $x;

}
9
myTest(5);
By: Berihun. M (Lecturer (MSc IT), (BSc CS))

?>
myTest();

myTest();

?>

PHP String Variables

A string variable is used to store and manipulate text.

String Variables in PHP

String variables are used for values that contain characters. After we have created a string variable we can manipulate it. A string can be used
directly in a function or it can be stored in a variable. In the example below, we create a string variable called txt, then we assign the text "Hello
world!" to it. Then we write the value of the txt variable to the output:

Example

<?php  Note: When we assign a text value to a variable, remember to put single or
double quotes around the value.
$txt="Hello world!";

echo $txt;

?>

The following are some commonly used functions and operators to manipulate strings.

The PHP Concatenation Operator

There is only one string operator in PHP.

The concatenation operator (.) is used to join two string values together. The example below shows how to concatenate two string variables
together:

Example
The output of the code above will be:

Hello world! What a nice day! 10


By: Berihun. M (Lecturer (MSc IT), (BSc CS))
Tip: In the code above we have used the concatenation operator two times. This is
because we wanted to insert a white space between the two strings.
<?php

$txt1="Hello world!";

$txt2="What a nice day!";

echo $txt1 . " " . $txt2;

?>

The PHP strlen( ) function

Sometimes it is useful to know the length of a string value.

The strlen( ) function returns the length of a string, in characters. The example below returns the length of the string "Hello world!":

Example
The output of the code above will be: 12
<?php
Tip: strlen( ) is often used in loops or other functions, when it is important to know when
echo strlen("Hello world!");
a string ends. (i.e. in a loop, we might want to stop the loop after the last character in a
?>
string).
The PHP strpos ( ) function

The strpos( ) function is used to search for a character or a specific text within a string. If a match is found, it will return the character position of
the first match. If no match is found, it will return FALSE. The example below searches for the text "world" in the string "Hello world!":

Example

<?php The output of the code above will be: 6

echo strpos("Hello world!","world");Tip: The position of the string "world" in the example above is 6. The reason
that it is 6 (and not 7), is that the first character position in the string is 0, and
?> not 1.

11
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
PHP Operators

The assignment operator = is used to assign values to variables in PHP.

The arithmetic operator + is used to add values together in PHP.

PHP Arithmetic Operators

Operator Name Description Example Result

x+y Addition Sum of x and y 2+2 4

x-y Subtraction Difference of x and y 5-2 3

x*y Multiplication Product of x and y 5*2 10

x/y Division Quotient of x and y 15/5 3

x%y Modulus Remainder of x divided by y 10 % 8 2

-x Negation Opposite of x -2 2

a.b Concatenation Concatenate two strings “hi”.”dear” hi dear

PHP Assignment Operators

The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the expression on the right. That is, the value of
"$x = 5" is 5.

Assignment Same as... Description

x=y x=y the left operand gets set to the value of the expression on the right

x += y x=x+y Addition

12
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
x -= y x=x-y Subtraction

x *= y x=x*y Multiplication

x /= y x=x/y Division

x %= y x=x%y Modulus

a .= b a=a.b Concatenate two strings

PHP Incrementing/Decrementing Operators

Operator Name Description

++ x Pre-increment Increments x by one, then returns x

x ++ Post-increment Returns x, then increments x by one

-- x Pre-decrement Decrements x by one, then returns x

x -- Post-decrement Returns x, then decrements x by one

PHP Comparison Operators

Comparison operators allows us to compare two values:

Operator Name Description Example

x == y Equal True if x is equal to y 5==8 returns false

x === y Identical True if x is equal to y, they are of same type 5==="5" returns false

x!= y Not equal True if x is not equal to y 5!=8 returns true

x <> y Not equal True if x is not equal to y 5<>8 returns true

x !== y Not identical True if x is not equal to y,or they are not of same type 5!=="5" returns true

13
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
x>y Greater than True if x is greater than y 5>8 returns false

x<y Less than True if x is less than y 5<8 returns true

x >= y Greater or equal True if x is greater than or equal to y 5>=8 returns false

x <= y less than or equal True if x is less than or equal to y 5<=8 returns true

PHP Logical Operators

Operator Name Description Example

x and y And True if both x and y are true x=6,y=3 (x < 10 and y > 1) returns true

x or y Or True if either or both x and y are true x=6,y=3, (x==6 or y==5) returns true

x xor y Xor True if either x or y is true, but not both x=6,y=3, (x==6 xor y==3) returns false

x && y And True if both x and y are true x=6,y=3, (x < 10 && y > 1) returns true

x || y Or True if either or both x and y are true x=6,y=3, (x==5 || y==5) returns false

!x Not True if x is not true x=6,y=3, !(x==y) returns true

PHP Conditional Statements

Very often when we write code, we want to perform different actions for different decisions. We can use conditional statements in our code to do
this.

In PHP we have the following conditional statements:

 if statement - executes some code only if a specified condition is true


 if...else statement - executes some code if a condition is true and another code if the condition is false
 if...else if....else statement - selects one of several blocks of code to be executed
 switch statement - selects one of many blocks of code to be executed

14
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
The If...Else Statement

If you want to execute some code if a condition is true and another code if a condition is false, use the if....else statement.

Syntax

if (condition)

code to be executed if condition is true;

else

code to be executed if condition is false;

Example

The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will output "Have a nice day!":
If more than one line should be executed if a condition is true/false, the lines
<html> should be enclosed within curly braces:

<body> <?php

<?php $d=date("D");

$d=date("D"); if ($d=="Fri")

if ($d=="Fri") {

echo "Have a nice weekend!"; echo "Hello!<br />";

else echo "Have a nice weekend!";

echo "Have a nice day!"; echo "See you on Monday!";

?> }

</body> ?>

15
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
</html>

The Else… If Statement

If you want to execute some code if one of several conditions are true use the elseif statement

Syntax

if (condition)

code to be executed if condition is true;

elseif (condition)

code to be executed if condition is true;

else

code to be executed if condition is false;

Example

The following example will output "Have a nice weekend!" if the current day is Friday, and

"Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!":

<?php
** Note: no space between else and if.
$d=date("D");
So in this we actually have 3 option to go based on the day today.
if ($d=="Fri")

echo "Have a nice weekend!";

elseif ($d=="Sun")

echo "Have a nice Sunday!";

16
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
else

echo "Have a nice day!";

?>

PHP Switch Statement

The Switch statement in PHP is used to perform one of several different actions based on one of several different conditions. If you want to select
one of many blocks of code to be executed, use the Switch statement. The switch statement is used to avoid long blocks of if..else code.

Syntax

switch (expression)

case label1:

code to be executed if expression = label1;

break;

case label2:

code to be executed if expression = label2;This is how it works:

break;  A single expression (most often a variable) is evaluated once


 The value of the expression is compared with the values for each case
default: in the structure
code to be executed  If there is a match, the code associated with that case is executed
 After a code is executed, break is used to stop the code from running
if expression is different into the next case
 The default statement is used if none of the cases are true
from both label1 and label2;

17
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
}

Example

<?php

switch ($x)

{ If you assign $x as 5 i.e $x=5;


case 1: The output will be
echo "Number 1"; No number between 1 and 3
break;

case 2:

echo "Number 2";

break;

case 3:

echo "Number 3";

break;

default:

echo "No number between 1 and 3";

?>

Looping

18
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
Bounded loops versus unbounded loops

A bounded loop executes a fixed number of times —you can tell by looking at the code how many times the loop will iterate, and the language
guarantees that it won’t loop more times than that. An unbounded loop repeats until some condition becomes true (or false), and that condition is
dependent on the action of the code within the loop. Bounded loops are predictable, whereas unbounded loops can be as tricky as you like.

PHP doesn’t actually have any constructs specifically for bounded loops —while, do-while, and for are all unbounded constructs —but an
unbounded loop can do anything a bounded loop can do.

While

The simplest PHP looping construct is while, which has the following syntax:

while (condition)

statement

The while loop evaluates the condition expression as a Boolean —if it is true, it executes statement and then starts again by evaluating condition.
If the condition is false, the while loop terminates. Of course, just as with if, statement may be a single statement or it may be a brace-enclosed
block. The body of a while loop may not execute even once, as in:

while (FALSE)

print(“This will never print.<BR>”);

Or it may execute forever, as in this code snippet:

while (TRUE)

print(“All work and no play makes Jack a dull boy.<BR>”);

or it may execute a predictable number of times, as in:

$count = 1;

while ($count <= 10)

19
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
{

print(“count is $count<BR>”);

$count = $count + 1;

which will print exactly 10 lines.

Do-while

The do-while construct is similar to while, except that the test happens at the end of the loop. The syntax is:

do statement

while (expression);

The statement is executed once, and then the expression is evaluated. If the expression is true, the statement is repeated until the expression
becomes false. The only practical difference between whileand do-whileis that the latter will always execute its statement at least once.For
example:

$count = 45;

do

print(“count is $count<BR>”);

$count = $count + 1;

while ($count <= 10)

This prints the single line:

20
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
Output will be 45.

For Loop

The most complicated looping construct is for, which has the following syntax:

for (initial-expression;termination-check; loop-end-expression)

statement;

It is also legal to include more than one of each kind of for clause, separated by commas.

The termination-check will be considered to be true if any of its sub clauses are true; it is like an ‘or’ test. For example, the following statement:

for ($x = 1, $y = 1, $z = 1; //initial expressions


Would give the browser output:
$y < 10, $z < 10; // termination checks
1, 1, 1
$x = $x + 1, $y = $y + 2, // loop-end expressions
2, 3, 4
$z = $z + 3)
3, 5, 7
print(“$x, $y, $z<BR>”);

Looping examples
create a Division Table using for loop.

<HTML>

<BODY>

<TABLE BORDER=1>

<?php

$start_num = 1;

21
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
$end_num = 10;

print("<TR>");

print("<TH> </TH>");

for ($count_1 = $start_num;

$count_1 <= $end_num;

$count_1++)

print("<TH>$count_1</TH>");

print("</TR>");

for ($count_1 = $start_num;

$count_1 <= $end_num;

$count_1++)

print("<TR><TH>$count_1</TH>");

for ($count_2 = $start_num;

$count_2 <= $end_num;

$count_2++)

$result = $count_1 / $count_2;

printf("<TD>%.3f</TD>", $result);

22
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
}

print("</TR>\n");

?>

</TABLE>

</BODY> </HTML>

PHP Arrays

An array can store one or more values in a single variable name.

What is an array?

When working with PHP, sooner or later, you might want to create many similar variables. Instead of having many similar variables, you can store
the data as elements in an array. Each element in the array has its own ID so that it can be easily accessed. There are three different kind of arrays:

 Numeric array- An array with a numeric ID key


 Associative array- An array where each ID key is associated with a value
 Multidimensional array- An array containing one or more arrays

Numeric Arrays

A numeric array stores each element with a numeric ID key. There are different ways to create a numeric array.

Example 1

In this example the ID key is automatically assigned:

$names = array("Tsegaye","Abebe","Joe");

Example 2

23
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
In this example we assign the ID key manually:

$names[0] = "Tsegaye";

$names[1] = "Abebe";

$names[2] = "Joe";

The ID keys can be used in a script:

<?php

$names[0] = "Tsegaye";

$names[1] = "Abebe";

$names[2] = "Joe";

echo $names[1] . " and " . $names[2] . " are ". $names[0] . "'s neighbors";

?>

Output: Abebe and Joe are Tsegaye’s neighbors.

Associative Arrays

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.

Example 1

In this example we use an array to assign ages to the different persons:

$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);

Example 2

24
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
This example is the same as example 1, but shows a different way of creating the array:

$ages['Peter'] = "32";

$ages['Quagmire'] = "30"; The code above will output:


$ages['Joe'] = "34"; Peter is 32 years old.
The ID keys can be used in a script:

<?php

$ages['Peter'] = "32";

$ages['Quagmire'] = "30";

$ages['Joe'] = "34";

echo "Peter is " . $ages['Peter'] . " years old.";

?>

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.

Example

In this example we create a multidimensional array, with automatically assigned ID keys:

$families = array

("Griffin"=>array("Peter", "Lois", "Megan"),"Quagmire"=>array("Glenn"), "Brown"=>array("Cleveland", "Loretta", "Junior"));

The array above would look like this if written to the output:

Array

25
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
([Griffin] => Array([0] => Peter[1] => Lois[2] => Megan) [Quagmire] => Array([0] => Glenn) [Brown] => Array([0] => Cleveland[1] =>
Loretta[2] => Junior) )

The foreach Statement

The foreach statement is used to loop through arrays.

For every loop, the value of the current array element is assigned to $value (and the array pointer is moved by one) - so on the next loop, you'll be
looking at the next element.

Syntax

foreach (array asvalue)

code to be executed;

Example

The following example demonstrates a loop that will print the values of the given array:

<?php

$arr=array("one", "two", "three");

foreach ($arr as $value)

echo "Value: " . $value . "<br />";

?>

26
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
PHP Functions

The real power of PHP comes from its functions. In PHP - there are more than 700 built-in functions available.

For a reference and examples of the built-in functions, please visit our PHP Reference.

Create a PHP Function

A function is a block of code that can be executed whenever we need it.

Creating PHP functions:

 All functions start with the word "function()"


 Name the function - It should be possible to understand what the function does by its name. The name can start with a letter or underscore (not
a number)
 Add a "{" - The function code starts after the opening curly brace
 Insert the function code
 Add a "}" - The function is finished by a closing curly brace.

Example

A simple function that writes my name when it is called:

<?php

function writeMyName()

echo "Tsegaye Andargie";

writeMyName();

?>

27
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
PHP Functions - Adding parameters

Our first function (writeMyName()) is a very simple function. It only writes a static string.

To add more functionality to a function, we can add parameters. A parameter is just like a variable.

You may have noticed the parentheses after the function name, like: writeMyName(). The parameters are specified inside the parentheses.

Example 1

The following example will write different first names, but the same last name:

<?php

function writeMyName($fname)

{ We can call a function as many times as we want.

echo $fname . "<br />"; The output of the program will be

} My name is Tsegaye

echo "My name is "; My name is Andargie

writeMyName("Tsegaye");

echo "My name is ";

writeMyName("Andargie");

?>

Example 2

The following function has two parameters:

<?php

28
By: Berihun. M (Lecturer (MSc IT), (BSc CS))
function writeMyName($fname,$punctuation)

{ echo $fname . " Refsnes" . $punctuation . "<br />"; }

echo "My name is "; The output of the code above will be:

writeMyName("Kai Jim","."); My name is Kai Jim Refsnes.

echo "My name is "; My name is Hege Refsnes!

writeMyName("Hege","!"); My name is Ståle Refsnes...

echo "My name is ";

writeMyName("Ståle","...");

?>

PHP Functions - Return values]

Functions can also be used to return values.

Example

<?php
The output of the code above will be:
function add($x,$y)
1 + 16 = 17
{ $total = $x + $y;

return $total;

echo "1 + 16 = " . add(1,16)

?>

29
By: Berihun. M (Lecturer (MSc IT), (BSc CS))

You might also like