0% found this document useful (0 votes)
117 views

Web Design, Programmig and Administration

Uploaded by

Young Uther
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
117 views

Web Design, Programmig and Administration

Uploaded by

Young Uther
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

COURSE: WEB DESIGN, PROGRAMMING AND ADMINISTRATION

COURSE CODE:

LECTURER: MR ARAKA GEOFFREY

BCS&BIT 2.2- Mr.Araka Page 1


WEB DESIGN, PROGRAMMING AND ADMINISTRATION

UNIT 1 : INTRODUCTION

All students should be familiar with the concepts of html and cascading stylesheets.

The following software is required to study PHP:

• A code editor. A code editor is a text editor that is specifically designed for writing code. It
provides features such as syntax highlighting, code completion, and debugging tools. Some
popular code editors include Visual Studio Code, Sublime Text, and Atom.
• A web development environment (WDE). A WDE is a software environment that allows you to
develop web applications locally on your computer. It includes a web server, database server,
and PHP interpreter. Some popular WDEs include WAMP,XAMPP, LAMP, and MAMP.
• A web browser. A web browser is used to view the results of your PHP code. Any modern web
browser, such as Google Chrome, Mozilla Firefox, or Microsoft Edge, will work.

Optional software that can be helpful for studying PHP includes:

• A version control system (VCS). A VCS is a system that allows you to track changes to your
code and collaborate with other developers. Some popular VCSs include Git and Mercurial.
• A debugger. A debugger is a tool that allows you to step through your code line by line and
inspect the values of variables. This can be helpful for finding and fixing bugs in your code.
Some popular debuggers include Xdebug and PHP Debugger.
• A documentation generator. A documentation generator is a tool that can generate
documentation for your PHP code. This can be helpful for documenting your code and making it
easier to understand and maintain. Some popular documentation generators include
phpDocumentor and Sphinx.
PHP is a powerful tool for making dynamic and interactive Web pages. PHP is the widely-used,
free, and efficient alternative to competitors such as Microsoft's ASP.

What is PHP?

It allows web developers to create dynamic content that interacts with databases. PHP is
basically used for developing web based software applications.

• PHP stands for PHP: Hypertext Preprocessor

• PHP is a server-side scripting language, like ASP .

BCS&BIT 2.2- Mr.Araka Page 2


A scripting language is a programming language that is interpreted..its translated into machine
code when the code is run. All scripting languages are programming languages but not all
programming languages are scripting languages.

• PHP scripts are executed on the server

• PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic
ODBC, etc.)

• PHP is an open source software

• PHP is free to download and use

What is a PHP File?

• PHP files can contain text, HTML tags and scripts

• PHP files are returned to the browser as plain HTML

• PHP files have a file extension of ".php", ".php3", or ".phtml"

What is MySQL?

• MySQL is a database server

• MySQL is ideal for both small and large applications

• MySQL supports standard SQL

• MySQL compiles on a number of platforms. PHP is compatible with almost all servers used
today (Apache, IIS, etc.)

• MySQL is free to download and use

PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a
Unix platform). PHP runs on different platforms (Windows, Linux, Unix, etc.)

BCS&BIT 2.2- Mr.Araka Page 3


Where is PHP used?

Three are the main areas where PHP scripts are used:

• Server-side scripting

This is the most used and main target for PHP. You need three things to make this work the way
you need it. The PHP parser (CGI or server module), a web server and a web browser.

You need to run the web server where You can access the PHP program output with a web
browser, viewing the PHP page through the server. All these can run on your home machine if
you are just experimenting with PHP programming.

• Command line scripting

You can make a PHP script to run it without any server or browser. You only need the PHP
parser to use it this way. This type of usage is ideal for scripts regularly executed using cron (on
Linux) or Task Scheduler (on Windows). These scripts can also be used for simple text
processing tasks.

• Writing desktop applications

PHP may not the very best language to create a desktop application with a graphical user
interface, but if you know PHP very well, and would like to use some advanced PHP features in
your client-side applications you can also use PHP-GTK to write such programs. You also have
the ability to write cross-platform applications this way. In this article, we’ll have a detailed look
at the server-side scripting using PHP.

Why PHP?

Why PHP is so popular today:

• Compatible with almost all servers used nowadays

A web server is an information technology that processes requests via HTTP, the basic network
protocol used to distribute information on the World Wide Web. There exist many types of web
servers that servers use. Some of the most important and well-known are: Apache HTTP Server,
IIS (Internet Information Services), lighttpd, Sun Java System Web Server etc. As a matter of
fact, PHP is compatible with all these web servers and many more.

• PHP will run on most platforms

Unlike some technologies that require a specific operating system or are built specifically for
that, PHP is engineered to run on various platforms like Windows, Mac OSX, Linux, Unix etc)

BCS&BIT 2.2- Mr.Araka Page 4


• PHP supports such a wide range of databases

An important reason why PHP is so used today is also related to the various databases it supports
(is compatible with). Some of these databases are: DB++, dBase, Ingres, Mongo, MaxDB,
MongoDB, mSQL, Mssql, MySQL, OCI8, PostgreSQL, SQLite, SQLite3 and so on.

• PHP is free to download and open source

Anyone can start using PHP right now by downloading it from php.net. Millions of people are
using PHP to create dynamic content and database-related applications that make for outstanding
web systems. PHP is also open source, which means the original source code is made freely
available and may be redistributed and modified.

• Easy to learn & large community

PHP is a simple language to learn step by step. This makes it easier for people to get engaged in
exploring it. It also has such a huge community online that is constantly willing to help you
whenever you’re stuck (which actually happens quite a lot).

The following is a list of popular PHP frameworks

• Laravel
• Symfony
• Yii
• CodeIgniter
• Laminas Project (formerly Zend Framework)
• CakePHP
• Phalcon
• Slim Framework
• FuelPHP
• PHPPixie
• Fat-Free Framework

As of today, the following PHP versions are available:

• Supported versions:

BCS&BIT 2.2- Mr.Araka Page 5


o PHP 8.2 (latest)
o PHP 8.1 (security fixes only)
o PHP 8.0 (security fixes only)
• Unsupported versions:
o PHP 7.4
o PHP 7.3
o PHP 7.2

Advantages of PHP

The popularity of PHP is growing rapidly because of its many advantages:

• It’s fast. Because it is embedded in HTML code, the response time is short.
• It’s inexpensive — free, in fact. PHP is proof that free lunches do exist and that you can
get more than you paid for.
• It’s easy to use. PHP contains many special features and functions needed to create
dynamic Web pages. The PHP language is designed to be included easily in an HTML
file.
• It can run on many operating systems. It runs on a variety of operating systems —
Windows, Linux, Mac OS, and most varieties of Unix.
• It’s available on almost all Web hosts. If you are going to publish your Web site on a
Web host, you will find PHP installed on almost all Web hosts for free.
• Technical support is widely available. A large base of users provides free support
through e-mail discussion lists.
• It’s secure. The user does not see the PHP code.
• It’s designed to support databases. PHP includes functionality designed to interact
with specific databases. It relieves you of the need to know the technical details required
to communicate with a database.
• It’s customizable. The open source license allows programmers to modify the PHP
software, adding or modifying features as needed to fit their own specific environments

BCS&BIT 2.2- Mr.Araka Page 6


Understanding PHP Basics

Learning a new language is not easy. You need to understand not only the syntax of the
language, but also its grammatical rules, that is, when and why to use each element of the
language

PHP code is executed on the server, and the plain HTML result is sent to the browser.

Basic PHP Syntax

A PHP scripting block always starts with ..

For maximum compatibility, we recommend that you use the standard form

A PHP file normally contains HTML tags, just like an HTML file, and some PHP scripting code

There are four ways the PHP parser engine can differentiate PHP code in a webpage:

• Canonical PHP Tags This is the most popular and effective PHP tag style and looks like this:

<?php…..?>

• Short-open Tags

These are the shortest option, but they might need a bit of configuration, and you might either
choose the --enable-shorttags configuration option when building PHP, or set the short_open_tag
setting in your php.ini file.

<?. .. ... ?>

• ASP-like Tags

In order to use ASP-like tags, you’ll need to set the configuration option in the php.ini file:

<%.........%>

• HTML script Tags

You can define a new script with an attribute language like so:

<script language=”php”>……..</script>

BCS&BIT 2.2- Mr.Araka Page 7


<?
print("Hello World");
echo "Hello World";
printf("Hello World");
?>

The result of the above statements would be the same: "Hello World". But why are there three
different ways to output?

• print returns a value. It always returns 1.


• echo can take a comma delimited list of arguments to output.
• printf is a direct analog of C’s printf().

echo and print are more or less the same. They are both used to output data to the screen. The
differences are small: echo has no return value while print has a return value of 1 so it can be
used in expressions. echo can take multiple parameters (although such usage is rare) while print
can take one argument. echo is marginally faster than print.
Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to
distinguish one set of instructions from another. There are two basic statements to output text
with PHP: echo and print. In the example above we have used the echo statement to output the
text "Hello World"

Note: The file must have a .php extension. If the file has a .html extension, the PHP code will
not be executed.

Commenting PHP
Just like other languages, there are several ways to comment PHP code.
Let’s have a look at the most useful ones:

Use # to write single-line comments


Eg

BCS&BIT 2.2- Mr.Araka Page 8


<?
# this is a comment in PHP, a single line comment
?>

Use // to also write single-line comments


<?
// this is also a comment in PHP, a single line comment
?>

Use /* ...*/ to write multi-line comments


<?
/*
this is a multi line comment
Name: Web Code Geeks
Type: Website
Purpose: Web Development
*/
?>

BCS&BIT 2.2- Mr.Araka Page 9


UNIT 2: VARIABLES ,OPERATORS AND EXPRESSIONS

Variables in PHP

Variables are the building blocks of any programming language. A variable can be thought of as
a programming construct used to store both numeric and nonnumeric data. The contents of a
variable can be altered during program execution, and variables can be compared and
manipulated using operators.

A variable is used to store information. Variable names in PHP are case-sensitive. As a result the
variables $color, $Color and $COLOR are treated as three different variables.

Variables are used for storing values, like text strings, numbers or arrays. When a variable is
declared, it can be used over and over again in your script.

All variables in PHP start with a $ sign symbol.

The correct way of declaring a variable in PHP.

$var_name = value;

In PHP, variables do not need to be declared before assignment.

The main data types used to construct variables are:

1. Integers -
▪ They are whole numbers, without a decimal point, like 4195.
▪ They are the simplest type.
▪ They correspond to simple whole numbers, both positive and negative.
Integers can be assigned to variables, or they can be used in expressions,
like $int_var = 12345;$another_int = -12345 + 12345;
▪ Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base
16) format. Decimal format is the default, octal integers are specified with
a leading 0, and hexadecimals have a leading 0x.
2. Doubles –
▪ floating-point numbers like 46.2, 733.21 etc
▪ They like 3.14159 or 49.1. By default, doubles print with the minimum
number of decimal places needed.
3. Booleans -
▪ They have only two possible values either true or false.
▪ PHP provides a couple of constants especially for use as Booleans: TRUE
and FALSE,
4. Strings - set of characters, like KIUT
5. Arrays - named and indexed collections of other values

BCS&BIT 2.2- Mr.Araka Page 10


6. Objects - instances of predefined classes
7. NULL – For variable that have not be given a value or have been unset
▪ NULL is a special type that only has one value: NULL.
▪ To give a variable the NULL value, simply assign it like this $my_var =
NULL;
▪ The special constant NULL is capitalized by convention, but actually it is
case insensitive; you could just as well have typed $my_var = null;
8. Resource – external resources like DB connections or file pointers

Testing for a Specific Data Type


PHP provides a special function corresponding to each data type.
These functions accept a variable or value and return a Boolean

There are numerous functions available for determining the data type of variables

• getType( )
• is_array( )- Returns true if the argument is an array
• is_double( )- Returns true if the argument is a double
• is_float( ), is_real( )
• is_long( ),
• is_int( )-Returns true if the argument is an integer
• is_string( )- Returns true if the argument is a string
• is_object( )- Returns true if the argument is an object
• is_resource( )- Returns true if the argument is a resource
• is_null( )- Returns true if the argument is null
• is_scalar( ) – check for integer, Boolean, string, or float
• is_numeric( ) – check for number or numeric string
• is_callable( ) – checks for valid function name
• is_bool() -Returns true if the argument is boolean

Each of these takes a variable as an argument and returns true or false

There is also a settype( $var, ‘type’ ) function that can be used to set a specific type

BCS&BIT 2.2- Mr.Araka Page 11


• Type can also be manipulated through the use of casting

// Casting

$totalamount = (float)$totalqty;

The following snippet shows all of these data types declared as variables:

<?

$intNum = 472;

$doubleNum = 29.3;

$boolean = true;

$string = ’bcs’;

$array = array("Pineapple", "Grapefruit", "Banana");

// creating a class before declaring an object variable

class person {

function agePrint() {

$age = 5;

echo "This person is $age years old!";

// creating a new object of type person

$object = new person;

?>

Naming Rules for Variables

• A variable name must start with a letter or an underscore "_"

• A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and
_)

BCS&BIT 2.2- Mr.Araka Page 12


• A variable name should not contain spaces. If a variable name is more than one word, it should
be separated with an underscore ($my_string), or with capitalization ($myString)

Variable Scope

• At this point we know that all variables have an identifier, a data type, and a value.
• All variables also have a scope.
o The scope of a variable refers to the places in a script where a variables can be
used.

In PHP, variables can be declared anywhere in the script. The scope of a variable
is the part of the script where the variable can be referenced/used.
PHP has three different variable scopes:
• local
• global
• static

Global and Local Scope


A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside
a function:

<!DOCTYPE html>
<html>
<body>
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>
</body>
</html>
A variable declared within a function has a LOCAL SCOPE and can only be
accessed within that function:

<!DOCTYPE html>
<html>
<body>
<?php
function myTest() {
$x = 5; // local scope

BCS&BIT 2.2- Mr.Araka Page 13


echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
?>
</body>
</html>

PHP The global Keyword


The global keyword is used to access a global variable from within a function.
To do this, use the global keyword before the variables (inside the function):
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest(); // run function
echo $y; // output the new value for variable $y
?>
</body>
</html>

PHP The static Keyword


Normally, when a function is completed/executed, all of its variables are
deleted. However, sometimes we want a local variable NOT to be deleted. We
need it for a further job.
To do this, use the static keyword when you first declare the variable:
<!DOCTYPE html>
<html>
<body>
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
echo "<br>";
myTest();

BCS&BIT 2.2- Mr.Araka Page 14


echo "<br>";
myTest();
echo "<br>";
myTest();
echo "<br>";
myTest();
?>
</body>
</html>
Then, each time the function is called, that variable will still have the
information it contained from the last time the function was called.

Example code on variables

PHP can be used for creating dynamic websites. In a dynamic website, user can
interact with website by providing text or by selecting options. Form is one of the
quickest and easiest ways to add interactivity to our website. Through forms we
can read user data into PHP variables.

Sample form

Home.html

< html>

< head>

< body>

< form action=" message . PHP" method =" post"> Enter your message:

< input type=" text" name=" MSG"=" 30">

< input type=" submit" value=" send ">

</ form>

</ body>

</ html>

Message. php

<? PHP

BCS&BIT 2.2- Mr.Araka Page 15


// retrieve form data in a variable

$input=$- post[" MSG"];

// print it

echo " you said <i> $input </i>”

?>

Output

You said: Hello

Explanation

Here we have used HTML coding for displaying the input box. The <form> tag of
html isused with input option. The form tag also contains two main attributes
action and method.

The action attribute specifies the name of the script. Here the name is
message.php. The script will process the message entered into the form. The
method attribute of the < form> tag specifies the manner in which form data will
be submitted. Here it is POST method.

We have to run the home.html file in a browser. This is a client side script. On
running this file a form is displayed in the webpage with a line.When we click the
submit button the server side script in the action attribute will be called for
execution. That script will display another webpage that prints the string we have
entered.The $_POST variable would have stored the string we have entered. It
will be stored in $_POST[‘msg’]. Then it will be assigned to php variable
$input.We can display it using echo statement

Constants

Constants are like variables except that once they are defined they cannot be
changed or undefined.

A constant is an identifier (name) for a simple value. The value cannot be


changed during the script.

A valid constant name starts with a letter or underscore (no $ sign before the
constant name). Note: Unlike variables, constants are automatically global across
the entire script.

BCS&BIT 2.2- Mr.Araka Page 16


Create a PHP Constant

To create a constant, use the define() function.

Syntax

define(name, value, case-insensitive)

Parameters:

name: Specifies the name of the constant

value: Specifies the value of the constant

case-insensitive: Specifies whether the constant name should be case-

insensitive. Default is false

The example below creates a constant with a case-sensitive name:

<!DOCTYPE html>

<html>

<body>

<?php

// case-sensitive constant name

define("GREETING", "Welcome to Tanzania!");

echo “GREETING”;

?>

</body>

</html>

The example below creates a constant with a case-insensitive name:

<!DOCTYPE html>

<html>

BCS&BIT 2.2- Mr.Araka Page 17


<body>

<?php

// case-insensitive constant name

define("GREETING", "Welcome to Tanzania", true);

echo greeting;

?>

</body>

</html>

NOTE

Constants are automatically global and can be used across the entire script.

Operators

PHP Operator is a symbol i.e used to perform operations on operands.

In simple words, operators are used to perform operations on variables or values.

PHP Operators can be categorized in following forms:

a. Arithmetic Operators

b. Assignment Operators

c. Bitwise Operators

d. Comparison Operators

e. Incrementing/Decrementing Operators

f. Logical Operators

g. String Operators

h. Array Operator

BCS&BIT 2.2- Mr.Araka Page 18


Arithmetic operators:

The PHP arithmetic operators are used to perform common arithmetic operations
such as addition, subtraction, etc. with numeric values.

Assignment Operators

The assignment operators are used to assign value to different variables. The basic
assignment operator is "=".

BCS&BIT 2.2- Mr.Araka Page 19


Bitwise operators

The bitwise operators are used to perform bit-level operations on operands. These
operators allow the evaluation and manipulation of specific bits within the integer.

Comparison Operators

Comparison operators allow comparing two values, such as number or string.


Below the list of comparison operators are given

BCS&BIT 2.2- Mr.Araka Page 20


Incrementing/Decrementing Operators

The increment and decrement operators are used to increase and decrease the
value of a variable.

BCS&BIT 2.2- Mr.Araka Page 21


Logical Operators

The logical operators are used to perform bit-level operations on operands. These
operators allow the evaluation and manipulation of specific bits within the integer.

String Operators

The string operators are used to perform the operation on strings. There are two
string operators in PHP, which are given below:

BCS&BIT 2.2- Mr.Araka Page 22


Operator precedence

You can add multiple operators to an expression to make it as long as it needs to


be, but you need to be careful as some operators have higher precedence than
others, and thus, the order of execution might not be the one you expect. The
following table shows the order of precedence of the operators

For example the expression 3+2*3 will first evaluate the product 2*3 and then the
sum, so the result is 9 rather than 15. If you want to perform operations in a
specific order, different from the natural order of precedence, you can force it by
enclosing the operation within parentheses. Hence, (3+2)*3 will first perform the
sum and then the product, giving the result 15 this time

BCS&BIT 2.2- Mr.Araka Page 23


UNIT 3: PHP CONTROL STRUCTURES

Control structures

▪ Control structure allows you to control the flow of code execution in your
application.
▪ Generally, a program is executed sequentially, line by line, and a control
structure allows you to alter that flow, usually depending on certain
conditions

PHP Conditional Statements

▪ Very often when you write code, you want to perform different actions for
different decisions. You can use conditional statements in your code to do this.
▪ Conditional statements are statements that can only be executed when a certain particular
condition is fulfilled.

a) The If statement
The if statement executes a piece of code if a condition is true. The syntax is

if (condition)
{
// code to be executed in case the condition is true
}

A practical example would be:

<?php
$age = 18;
if ($age < 20)
{
echo "You are a teenager";
}
?>

BCS&BIT 2.2- Mr.Araka Page 24


Example 2
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
{
echo "Hello!<br />";
echo "Have a nice weekend!";
echo "See you on Monday!";
}
?>
</body>
</html>

Note The code is executed only if the specified condition is true.

b) if...else Statement
Use the if....else statement to execute some code if a condition is true and another code if the
condition is false.

Syntax

if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}

Example

<html>
<body>
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else
{
echo "Have a good night!";
}
?>

BCS&BIT 2.2- Mr.Araka Page 25


</body>
</html>

c) if...elseif....else Statement
If you've got more than two choices to choose from, you can use the elseif statement.

Syntax
if (expression1)
{
// code is executed if the expression1 evaluates to TRUE
}
elseif (expression2)
{
// code is executed if the expression2 evaluates to TRUE
}
elseif (expression3)
{
// code is executed if the expression3 evaluates to TRUE
}
else
{
// code is executed if the expression1, expression2 and expression3 evaluates to FALSE, a
default choice
}

Example

<?php
$age = 50;
if ($age < 30)
{
echo "Your age is less than 30!";
}
elseif ($age > 30 && $age < 40)
{
echo "Your age is between 30 and 40!";
}
elseif ($age > 40 && $age < 50)
{
echo "Your age is between 40 and 50!";
}
else
{
echo "Your age is greater than 50!";
}
?>

BCS&BIT 2.2- Mr.Araka Page 26


d) Switch Statement
The switch statement is somewhat similar to the elseif statement which we've just discussed
in the previous section.
Use the switch statement to select one of many blocks of code to be executed.
The switch statement works with two other keywords: case and break. The case keyword is
used to test a label against a value from the round brackets. If the label equals to the value,
the statement following the case is executed. The break keyword is used to jump out of the
switch statement. There is an optional default statement. If none of the labels equals the
value, the default statement is executed

Syntax

switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}

This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each case in
the structure. If there is a match, the block of code associated with that case is executed. Use
break to prevent the code from running into the next case automatically. The default
statement is used if no match is found.

Example 1
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":

BCS&BIT 2.2- Mr.Araka Page 27


echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, or green!";
}
?>

Example 2

<?php
$domain = 'sk';
switch ($domain) {
case 'us':
echo "United States\n";
break;
case 'de':
echo "Germany\n";
break;
case 'sk':
echo "Slovakia\n";
break;
case 'hu':
echo "Hungary\n";
break;
default:
echo "Unknown\n";
break;
}

Looping Statements

Computers often have to do the same task repetitively until some condition is
satisfied. loops are used to execute the same code block for a specified number of times.

a)The for loop

The for loop is used when the programmer knows in advance how many times the block
of code should be executed. This is the most common type of loop encountered in almost
every programming language.

Syntax

for (initialization; condition; increment/decrement)


{
// executable code
}

BCS&BIT 2.2- Mr.Araka Page 28


Parameters:

• initiliation: Mostly used to set a counter (but can be any code to be executed once at the
beginning of the loop)
• condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues.
If it evaluates to FALSE, the loop ends.
• increment: Mostly used to increment a counter (but can be any code to be executed at
the end of the loop)
Note: Each of the parameters above can be empty, or have multiple expressions
(separated by commas).

Example
An example where we use the for loop would be:

<html>
<body>
<?php
for ($i=0; $i<=5; $i++)
{
echo "The number is " . $i . "<br />";
}
?>
</body>
</html>

The result of this code snippet would be:


This is loop number 0
This is loop number 1
This is loop number 2
This is loop number 3
This is loop number 4

b)The while Loop

The while loop executes a block of code while a condition is true.


Its also called an entry controlled loop

Syntax

while (condition)
{
code to be executed;
}

BCS&BIT 2.2- Mr.Araka Page 29


example
<html>
<body>
<?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;
}
?>
</body>
</html>
Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

c)The do...while Statement

The do...while statement will always execute the block of code once, it will then check
the condition,and repeat the loop while the condition is true.
Its also called an exit controlled loop

Syntax
do
{
code to be executed;
}
while (condition);

example
<html>
<body>
<?php
$i=1;
do
{
$i++;
echo "The number is " . $i . "<br />";
}
while ($i<=5);
?>

BCS&BIT 2.2- Mr.Araka Page 30


</body>
</html>

d) foreach Loop
The foreach loop works only on arrays, and is used to loop through each
key/value pair in an array.

Syntax

foreach ($array as $value)


{
code to be executed;
}

For every loop iteration, the value of the current array element is assigned to
$value and the array pointer is moved by one, until it reaches the last array
element.

The following example demonstrates a loop that will output the values of the
given array ($colors):

example

<!DOCTYPE html>
<html>
<body>
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) ``
{
echo "$value <br>";
}
?>
</body>
</html>

Arrays

Array is complex variable that enables us to store multiple values in a single variable. We use
this to store related information. An array is a special variable, which can hold more than one
value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables
could look like this:
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";

BCS&BIT 2.2- Mr.Araka Page 31


And what if you had not 3 cars, but 300?

The solution is to create an array! An array can hold many values under a single name, and you
can access the values by referring to an index number.

Create an Array in PHP


In PHP, the array() function is used to create an array:

In PHP, there are three types of arrays:


• Indexed arrays - Arrays with a numeric index
• Associative arrays - Arrays with named keys
• Multidimensional arrays - Arrays containing one or more arrays

PHP Indexed Arrays


There are two ways to create indexed arrays: The index can be assigned automatically (index
always starts at 0), like this:

$cars = array("Volvo", "BMW", "Toyota");

or
the index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota"

Example
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
</body>
</html>

Get The Length of an Array - The count() Function


The count() function is used to return the length (the number of elements) of an array:

<!DOCTYPE html>
<html>
<body>
<?php

BCS&BIT 2.2- Mr.Araka Page 32


$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
</body>
</html>

Loop Through an Indexed Array


To loop through and print all the values of an indexed array, you could use a
for loop, like this:

<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
for($x = 0; $x < $arrlength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
</body>
</html>

PHP Associative Arrays

Associative arrays are arrays that use named keys that you assign to them.
Also known as hash arrays

There are two ways to create an associative array:

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

or:

$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";

We access element by using the key instead of position number

BCS&BIT 2.2- Mr.Araka Page 33


The named keys can then be used in a script:

<!DOCTYPE html>
<html>
<body>
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
</body>
</html>

Loop Through an Associative Array

To loop through and print all the values of an associative array, you could use a
foreach loop, like this:

<!DOCTYPE html>
<html>
<body>
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
</body>
</html>

Multidimensional Arrays
A multidimensional array is an array containing one or more arrays.
PHP understands multidimensional arrays that are two, three, four, five, or
more levels deep. However, arrays more than three levels deep are hard to
manage for most people.

The dimension of an array indicates the number of indices you need to select an
element.

•For a two-dimensional array you need two indices to select an element


•For a three-dimensional array you need three indices to select an element

BCS&BIT 2.2- Mr.Araka Page 34


Two-dimensional Arrays
A two-dimensional array is an array of arrays (a three-dimensional array is an
array of arrays of arrays).
First, take a look at the following table:

We can store the data from the table above in a two-dimensional array, like
this:
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);

Now the two-dimensional $cars array contains four arrays, and it has two
indices: row and column.
To get access to the elements of the $cars array we must point to the two indices (row and
column):

<!DOCTYPE html>
<html>
<body>
<?php
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
</body>
</html>

BCS&BIT 2.2- Mr.Araka Page 35


We can also put a For loop inside another For loop to get the elements of the
$cars array (we still have to point to the two indices):
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}
?>
</body>
</html>

Sorting Arrays
The elements in an array can be sorted in alphabetical or numerical order,descending or
ascending.

Sort Functions For Arrays


The following are the PHP array sort functions:

▪ sort() - sort arrays in ascending order


▪ rsort() - sort arrays in descending order
▪ asort() - sort associative arrays in ascending order, according to the value
▪ ksort() - sort associative arrays in ascending order, according to the key
▪ arsort() - sort associative arrays in descending order, according to the value
▪ krsort() - sort associative arrays in descending order, according to the key

BCS&BIT 2.2- Mr.Araka Page 36


Sort Array in Ascending Order - sort()
The following example sorts the elements of the $cars array in ascending
alphabetical order
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
</body>
</html>

The following example sorts the elements of the $numbers array in ascending
numerical order:

<!DOCTYPE html>
<html>
<body>
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
echo $numbers[$x];
echo "<br>";
}
?>
</body>
</html>

BCS&BIT 2.2- Mr.Araka Page 37


Sort Array in Descending Order - rsort()
The following example sorts the elements of the $cars array in descending
alphabetical order:
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
</body>
</html>

The following example sorts the elements of the $numbers array in descending
numerical order:

<!DOCTYPE html>
<html>
<body>
<?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
echo $numbers[$x];
echo "<br>";
}
?>
</body>
</html>

BCS&BIT 2.2- Mr.Araka Page 38


UNIT 4 :PHP FUNCTIONS
A function is a set of program statements that perform a specific task. Functions can be
called or executed from anywhere in the program. All the programming languages have
built-in
functions and also allow us to create user defined function

Importance of using functions

1. Reducing repetition:

User defined function enables developer to extract commonly used pieces of code as separate
package. These functions help developers avoid redundant work and focus more on the logic
rather than routine things.

2. Easy maintenance:-

Because functions are defined once and used many times, they are used to maintain the code.
During code maintenance if we want to change from values in calculation, we need to change
only in the function. We need not Traverse the whole program for making change in one value.

3. Improves abstraction:

Function forces programmer to think in abstract terms. We need not worry about implementation
of the function. It is enough that we know the function name, number of arguments and return
type of the function.

Functions can be divided into two parts


• User defined functions- functions defined by the user

• Built-in functions
PHP has over 1000 built-in functions that can be called directly, from within a script, to
perform
a specific task

PHP User Defined Functions


Besides the built-in PHP functions, it is possible to create your own functions.

BCS&BIT 2.2- Mr.Araka Page 39


Create a User Defined Function in PHP

There are two parts which should be clear to you

• Creating a Function

• Calling a Function

The basic syntax to create a function is

<?php

function functionName($argument1, $argument2...) {

// code to be executed

functionName($argument1, $argument2...); // function call

?>

Note that while creating a function its name should start with keyword function and all the PHP
code should be put inside { and }, the arguments within the function are optional.

invoking function

<?php

….

….

displayShakesphearQuote();

?>

PHP functions are defined with the function keyword following by name of the function.

➢ The name of function should follow the rule for naming variables.

➢ After function name list of arguments enclosed in parenthesis() should be present.

➢ It is optional and can be omitted if no argument is present.

BCS&BIT 2.2- Mr.Araka Page 40


➢ After the first line of the function the body of the function should be present in between the
curly brackets {}.

➢ The function code can contain any valid PHP statements, which includes loops conditional
statements and call to other function.

➢ Invoking a function is done by calling a function with its name.

➢ If the function had arguments we have to specify the arguments during invoking

Example

<?php

//define a function

function displayQuote()

echo’some are born great, some achieve greatness and some have greatness through upon them’;.

displayQuote();

?>

Defining a Functions with Parameters and without Parameters

PHP gives you option to pass your parameters inside a function. You can pass as many as
parameters as you like.

Example of PHP script for function with argument.

<?php

//define a function

function triangle_area ($base,$height)

$area=$base*$height*0.5

return $area;

BCS&BIT 2.2- Mr.Araka Page 41


//invoke a function

$ta=triangle_area(10,50);

echo’the area of a triangle is $ta’;

?>

Another example function with arguments:

<?php

function greetPerson($name)

// function definition with arguments

echo "Hi there, ".$name;

// what this function does

greetPerson("Fabio"); // function call

greetPerson("Michael");

?>

More than one argument can be used in a function

example

<?php

function personProfile($name, $city, $job)

// function definition with arguments

echo "This person is ".$name." from ".$city.".";

echo "";

BCS&BIT 2.2- Mr.Araka Page 42


echo "His/Her job is ".$job.".";

personProfile("Fabio", "Tirana", "Web Dev");

echo "";

personProfile("Michael", "Athens", "Graphic Designer");

echo "";

personProfile("Xena", "London", "Tailor");

?>

Returning value from the function

A function can return a value using the return statement in conjunction with a value or object.
return stops the execution of the function and sends the value back to the calling code.

To let a function return a value, use the return statement:

You can return more than one value from a function using return array(1,2,3,4).

Example:

<html>

<head>

<title>Writing PHP Function which returns value</title>

</head>

<body>

<?php

function addFunction($num1, $num2) {

$sum = $num1 + $num2;

return $sum;

$return_value = addFunction(10, 20);

BCS&BIT 2.2- Mr.Araka Page 43


echo "Returned value from the function : $return_value";

?>

</body>

</html>

This will display following result −

Returned value from the function : 30

Types of errors in PHP

Basically, an error is a mistake in a program that may be caused by writing incorrect syntax or
incorrect code. An error message is displayed on your browser containing the filename along
with location, a message describing the error, and the line number in which error has occurred.

There are usually different types of error. In PHP, mainly four types of errors are considered:

1. Syntax Error or Parse Error

2. Fatal Error

3. Warning Error

4. Notice Error

Syntax Error or Parse Error

A syntax error is a mistake in the syntax of source code, which can be done by programmers due
to their lack of concern or knowledge. It is also known as Parse error. Compiler is used to catch
the syntax error at compile time.

Fatal Error

A fatal error is another type of error, which is occurs due to the use of undefined function. The
PHP interpreter understands the PHP code but also recognizes the undefined function. This
means that when a function is called without providing its definition, the PHP interpreter
generates a fatal error.

Warning Error

BCS&BIT 2.2- Mr.Araka Page 44


A warning is generated when the programmer tries to include a missing file. The PHP function
calls that missing file which does not exist. The warning error does not stop/prevent the
execution of the program. The main reason behind generating a warning error is to pass an
incorrect number of parameters to a function or to include a missing file

Notice Error

Notice error is same as warning error. When a program contains something wrong, the notice
error occurs. But it allows/continue the execution of the program with a notice error. Notice error
does not prevent the execution of the code. For example - access to undefined variable.

BCS&BIT 2.2- Mr.Araka Page 45

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy