Nothing Special   »   [go: up one dir, main page]

PHP CH-01

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 58

INTERNET PROGRAMMING-II)

CHAPTER – 01
INTERNET PROGRAMMING WITH PHP
Learning Outcomes
On successful completion of the course, the students should be able to:
Apply the Internet Programming design concepts in solving real world problems.

Identify the advantages and disadvantages of various Internet Programming


techniques to real world problems.
Implement server side database driven Internet applications using
PHP/MySQL/Web server.
Demonstrate knowledge of new and emerging internet programming technologies,
tools and techniques.
What you should know First
WWW (World Wide Web):
►It is a system of interlinked hypertext documents accessed via the Internet.
►Web is a huge collection of pages of information linked to each other around the globe

Web page – consists of objects (HTML file, image, Media) and addressed by URL

Website – a collection of web pages


Web App – a s/w or program which is accessible using any web browser. E.g google
docs

Web Governing Protocol:


►It is a set of rules that is used to communicate applications to each other. or
►It is the interface required for communicating the different applications.
►E.g. HTTP - is used to distribute information on the web.
Web Programming
It refers to the writing, markup and coding involved in Web development, which includes Web content,
Web client and server scripting, Database technology and network security.
Web Design:
►how the website looks and feels.
►model the layout of the website, making sure it’s logical, user-friendly and pleasant to use.
►They consider all the different visual elements(color, fonts, content and layout).

Web development:
►is the process of building websites and applications for the internet, or for a private network known as an
intranet.
►It is not concerned with the design of a website; rather, it’s all about the coding and programming that
powers the website’s functionality.
►Web development can be broken down into three layers:
1. Client-side coding (frontend)
2. Server-side coding (backend)
3. Database technology
Cont…
1. Client-side coding (frontend)
 refers to everything that the end user experiences directly.
 executes in a web browser and directly relates to what people see when they visit a website.
 Things like layout, fonts, colors, menus and contact forms are all driven by the frontend.
 Languages: HTML, CSS, JavaScript
2. Server-side coding (backend)
 is all about what goes on behind the scenes.
 Is part of a website that the user doesn’t actually see.
 It is responsible for storing and organizing data, and ensuring that everything on the client-side
runs smoothly.
 It does this by communicating with the frontend.
 Languages: PHP, Java, Python, Perl, ASP.NET, Ruby
3. Database technology
 Creating and maintaining a database
 MySQL, SQL Server, Postgres, Oracle
Scripting Languages(SL) - General
►Scripting languages are generally interpreted - compiles a code line by line.
►It is translated into machine code when the code is run, rather than beforehand.
►PHP, JavaScript, Python, and Ruby are all examples of scripting languages.
►“Easy to learn” and have support for high-level structures and libraries.
►Automatic memory management controls the allocation and freeing (garbage
collection) of memory on demand.
►Many scripting languages are starting to adopt object-oriented structures.
►Most modern scripting languages have built-in support for high level data structures.
►All scripting languages are programming languages, not all programming languages
are scripting languages.
►Two categories of Scripting Languages: Client-side Scripting and Server-side
Scripting
Client-side Scripting
►refers to the class of computer programs on the web that are executed on client-side,
by the user's web browser.
►It reduces demand on the server, allowing web pages to load faster.
►is more focused on user interface and functionality.
►are often embedded within an HTML or XHTML document (hence known as an
"embedded script"), but they may also be contained in a separate file.
►may also contain instructions for the browser to follow in response to certain user
actions, (e.g., clicking a button). Often, these instructions can be followed without
further communication with the server.
►E.g. HTML, CSS, JavaScript
Client Side Scripting
►Client Side Scripting performing tasks like:
 Make interactive user interface
 Validates user input
 Enhances Web pages with ActiveX® controls, applets, etc.
 Manipulates browser documents
 Reduces number of requests that need to be passed to server
 Browser dependency
Shortcomings of Client Side Scripting
►Browser support is inconsistent - for example VBScript is poorly supported by non-Microsoft
browsers
►The script must be passed from server to client across the network
►Security - the script is visible to client end-users
►Accessibility - content produced client-side is often "hidden" from associative technologies
such as screen readers
Server-side scripting languages
►It is any scripting or programming that can runs on a web server. When a client sends a
request, the server processes the request and responds by sending content via HTTP.
►Benefit - are not viewable by the public like client-side scripts are.
►Scripting focuses on faster processing, access to data, and resolving errors.
►originally developed to interface with databases or other data stores on the server.
►constructs a communication link between a server and a client (user).
►The web server abstracts the scripts from the end user until serving the content, which
makes the data and source code more secure.
►Performs operations like:
 customization of a website,
 dynamic change in the website content,
 response generation to the user’s queries,
 accessing the database
►E.g. PHP, ASP.NET, Python, Perl, JSP(Java Server Page),
Server-Side Scripting

►Advantages of Server-Side Scripting

Dynamic content, layout and behavior of Web

Computational capability( Efficient and Effective)

Database , file system access & network access (from the server only)

Built-in libraries and functions(The Power!)

Known platform for execution (as opposed to client-side, where the platform is
uncontrolled.) Independent of HW & SW
Security improvements
Sever-side scripting
►When evaluating which server-side technology to use, you need to consider a
number of critical factors
Ease of development
• How easily can you build new applications
Performance (responsiveness)
• How fast can the technology respond to queries
Scalability
• Can the technology scale to thousands, even millions of users?
Security
• Are there any inherent security vulnerabilities?
►The most widely used web servers are:
• Apache, nginx, Microsoft-IIS, Lighthttpd, Caddy, MonkeyServer, OpenLiteSpeed,
Cherokee, Jigsaw Server
Common Features
►All server-side frameworks share a common set of features
Read, Check and Validate data submitted by the user
Generate HTML dynamically based on user input
Determine information about the client browser
Access database systems, file systems, & other resources
Exploit the HTTP protocol
User does not need to download plugins like Java or Flash
Generally quicker to load than client-side scripting
User is able to include external files to save coding
Scripts are hidden from view so it’s more secure.
Server- side options -Dynamic Websites
►Dynamic websites shows different information at different point of time. It is possible to
change a certain portion of a web page without loading the entire web page. It has been made
possible using Ajax technology.

►Server-side dynamic web page is created by using server-side scripting such as PHP.

►Dynamic websites are websites that do more than just fetch and return files. Here are some
examples of what a dynamic site might do when it receives a request:
 Perform a database search and return a list of search results.

 Log a user into a website by checking the database for the user's credentials.

 Redirect the user to a login page if the user requests a members-only page.

 Record a user's support request in a database, email the user a friendly message & the auto-generated support ticket number.

 Stores persistent data


Server- side options -Dynamic Websites …
Server- side options -Application
Server- side options -Development
Server- side options –Scripting
Server-Side Architecture
.

Gets Page
WEB SERVER
<HTML>
<?php PHP code ?>
HTTP Request </HTML>
(url)
Server response Interprets the PHP code
<HTML>
<B>Hello</B>
CLIENT </HTML>
Hello
Browser creates
the web page

18
Introduction to PHP(Hypertext
Preprocessor)
• PHP stands for PHP: Hypertext Preprocessor

• It is a powerful server-side scripting language for creating dynamic & interactive website

• It is perfectly suited for Web development and can be embedded directly into the HTML code.

• PHP is often used together with Apache (web server) on various operating systems. It also supports IS-

API and can be used with Microsoft's IIS on Windows.

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

etc.)

• PHP scripts are executed on the server, the computer where the Web site is located.
PHP Features

Free, Open source server side scripting(interpreted) language

Can generate dynamic web page

Fairly easy but quite powerful!

Can be embedded within HTML code

Object Orientation supported

Supports (almost) all major databases and web servers (apache, IIS)

Run Faster on various platforms (windows, linux, unix, Mac, etc.)

Current version: PHP 8 (progress!)

Alternatively called Personal Home Pages


PHP (Hypertext Preprocessor)
.
Common uses of PHP
►What can PHP do?
►PHP performs system functions, i.e. from files on a system it can create, open, read, write, and close
them.
►PHP can handle forms, i.e. gather data from files, save data to a file, through email you can send data,
return data to the user.
►You add, delete, modify elements within your database through PHP.
►Access cookies variables and set cookies.
►Using PHP, you can restrict users to access some pages of your website.
 It can encrypt data.
 used to make web pages dynamic: provide different content depending on context interface with
other services: database, e-mail, etc authenticate users process form information.
►Characteristics of PHP
► Simplicity
► Efficiency
► Security
► Flexibility
 Familiarity
What You Need?
►In order to develop and run PHP Web pages, three vital components need to be installed
on your computer system.
 Web Server - PHP will work with virtually all Web Server software, including Microsoft's
Internet Information Server (IIS) but then most often used is freely available Apache Server.
 Database - PHP will work with virtually all database software, including Oracle and Sybase
but most commonly used is freely available MySQL database.
 PHP Parser - In order to process PHP script instructions, a parser must be installed to
generate HTML output that can be sent to the Web Browser.
Or
►Install XAMPP: stands for “Cross Platform(‘X’) Apache MySQL Php Perl”
 can be installed which will provide a bundle or suit of webserver, php and database software
for working with php.

►Install WAMPP: stands for “Windows Apache MySQL Php” can also be installed which
will work only on windows platform.
PHP – Language Basics(Syntax)
►PHP code can be embedded in HTML and all PHP code must be included inside one
of the following possible tags that are recognized by the PHP Parser.
 Canonical PHP tags
<?php PHP code goes here ?>
 Short-open (SGML-style) tags
<? PHP code goes here ?>
 HTML script tags
<script language="php"> PHP code goes here </script>
 ASP-style tags
<% PHP code goes here %>
►Hence, the PHP parser only parses code which is in between <?php and ?>

►Php files can be saved with .php extension in the server recognized directory i.e.
htdocs for Xampp and www for Wamp.
PHP – Language Basics
►PHP is whitespace insensitive
 it almost never matters how many whitespace characters you have in a row. one whitespace
character is the same as many such characters.
► PHP variables are case sensitive. E.g. $phpvar and $PHPVAR are different variables
►All user defined functions, classes and keywords (eg: if, else, echo, etc) are not case
sensitive.
► Statements are expressions terminated by semicolons(;)
► Expressions are combinations of tokens
►Tokens of PHP (variables, data types, functions, methods, objects, classes,
resources, packages(APIs) etc )
►Comments in PHP:
 Single Line Comment: enclosed in // or #. E.g. // This is a single line comment
 Multiple Line Comment: start with /* and end with */. E.g. /* This is a multiple line comment
*/
PHP – Language Basics -Examples
Variables & Data Types
<?php
Expressions & Operators
// PHP statements
?> Functions, Objects, Methods & Classes
Resources & Packages
►Web pages that contain PHP should be saved with .php extension.
Example :
<?php echo “This line brought to you by PHP”;?>
►When the Web server gets the file and sees the .php extension, it checks for PHP tags.
When it finds the PHP tag, it executes the PHP echo statement instead of sending it to
the browser.
►Echo & print: echo () or print () is a method used for displaying the html tags or
response with data back to the client.
►Echo() can accept many arguments but print() accepts only one argument.
►Echo() is faster than print()
PHP – Language Basics –Examples …
Example :
<html> <head><title>Hello World Script</title></head>
<body>
<?php
echo “<p>Hello World!</p>”
?>
</body> </html>
►When the PHP section is processed, it is replaced with the output. In this case, the
output is as follows:
<p>Hello World!</p>
►In your browser window, you see the output at the location in the page where you
added the PHP section. Even if you view the source in your browser, you only see the
output, not the PHP code.
Variables in PHP
►A variable is used to storing a values, like text strings, numbers or arrays. When a
variable is declared, it can be used over and over again in your script.
►Rules for naming a variable is same as in C++
►All variables start with “$” followed by name of the variables.
E.g. $var_name; or $var_name = value;
►PHP does a good job of automatically converting types from one to another when
necessary.
►The variable data type depends on the current value it holds
PHP Variable Types
►PHP Variable Types can be classified as: scalar , compound and special types.
►Integers − are whole numbers, without a decimal point, like 4195.
►Doubles − are floating-point numbers, like 3.14159 or 49.1.
►Booleans − have only two possible values either true or false.
 Strings − are sequences of characters, like PHP supports string operations.
 Arrays − are named and indexed collections of other values.
 Objects − are instances of programmer-defined classes, which can package up both other
kinds of values and functions that are specific to the class.
 NULL − is a special type that only has one value: NULL.
 Resources − are special variables that hold references to resources external to PHP (such
as database connections).
 Var_dump() and gettype() are the methods for finding the data type of the
variable. E.g. $x=NULL; var_dump($x); //NULL
Variable Scope
►Scope can be defined as the range of availability a variable has to the program in which
it is declared. PHP variables can be one of four scope types:
Local Variables - are variables declared in a function. Any assignment outside of
that function will be considered to be an entirely different variable from the one
contained in the function.
Function Parameters - Function parameters are declared after the function name
and inside parentheses.
Global Variables - can be accessed in any part of the program. This is done, by
placing the GLOBAL keyword in front of the variable. E.g. GLOBAL $num;
Static Variables - not lose its value when the function exits and will still hold that
value should the function be called again.
• This done by placing the STATIC keyword in front of the variable name.
• E.g. STATIC $num;
PHP Global Variables - Superglobals
►Several predefined variables in PHP are "superglobals", which are always accessible
regardless of scope - and from any function, class or file without having to do anything.
►There is no need to do global $variable; to access them within functions or methods.
►The PHP superglobal variables are:
►$GLOBALS - used to access global variables from anywhere in the PHP script.
►$_SERVER – Contains server and execution environment information.
►$_REQUEST - used to collect data after submitting an HTML form.
►$_POST - used to collect form data after submitting an HTML form with method="post".
►$_GET - used to collect form data after submitting an HTML form with method="get".
►$_FILES - HTTP File Upload variables
►$_COOKIE - stores variables passed to current script along with HTTP request
Constant Variables
►PHP is a loosely typed language – no need of declaration before use.
No variable declaration ( implicit ), to create a variable, just assign some value to
it!
Example: $myNum = 5; //declares and assignes 5 to the variable $myNum
►Constant variables:- defined by using define() method.
►It takes 3 arguments(name of the constant, value of the constant, case insensitive)

►The third argument is by default set to false. If it is true then the constant can be case
insensitive.

►Eg 1: define(“MAX”, 50, true)


►Echo max; // displays 50
►Echo MaX; // also displays 50 as the 3rd parameter is true.

►Eg 2: define(“MAX”, 50)


►Echo max; // error as the 3rd parameter is false.
Strings in PHP
►A string variable is used to store and manipulate a piece of text enclosed within single
or double quotation. E.g. $name=‘Hello World’; or $name=“Hello World”;
►Variables within double quoted strings (“ ”) are parsed
►Example: $name = “Abebe”;
echo “Hello $name”; //Hello Abebe
echo “Hello {$name}”; //Hello Abebe
echo “Hello ${name}”; //Hello Abebe
►Variables within single quoted strings (‘ ’) are not parsed!
echo ‘Hello $name’; //Hello $name
►String Concatenation: The concatenation operator (.) is used to put two string values
together.
►E.g. $var1 = “Today is “;
echo $var1 . date(“d-m-Y”); //Today is 20-03-2021
Cont…

►The strlen() function is used to find the length of a string.

E.g. echo strlen("Hello world!"); // displays 12

►The length of a string is often used in loops or other functions, when it is important
to know when the string ends.

►The strpos() function is used to search for a string or character within a string.

►If a match is found in the string, this function will return the position of the first
match. If no match is found, it will return FALSE.
E.g. echo strpos("Hello world!","world"); // displays 6
Operators in PHP

►Operators are used to operate on values.

►Arithmetic operators: +, - , *, / , %;

►Comparison operators: ==(equals), !=(not equals), >, <, >=, <=, ===(identical, true if
the variables used for comparison are both equal in value and also equal in datatype). !
==(not identical).

►Logical operators: &&(and), ||(or), !(not)

►Increment/Decrement operators: ++, --.

►String Concatenation operator: “ . “(dot).

►Ternary or Conditional operator: ? : E.g. echo(expr1 ? expr2 : expr3);


Control Structure in Php- Decision Making
►All control structure use the same logic as like other programming languages.

►if...else statement − use this statement if you want to execute a set of code when a
condition is true and another if the condition is not true

►elseif statement − is used with the if...else statement to execute a set of code if one of
the several condition is true

►switch statement − is used 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 if..else code.
Control Structure in Php- Decision Making

►The if statement executes some code if one condition is true.


$t = 10;
if ($t < 20){ echo “t is less than 20!"; }
►The if...else statement executes some code if a condition is true and another code if
►The if...elseif...else statement executes different
that condition is false. codes for more than two conditions.
$gender = “Male”; $t = date("H");
if ($t < "10") {
if ($ gender == “Male") {
echo "Have a good morning!";
echo “Gender is Male!"; } elseif ($t < "20") {
echo "Have a good day!";
} else {
} else {
echo “Gender is Female!"; echo "Have a good night!";
} }
Control Structure in Php- Decision Making

►The switch statement is used to perform different actions based on different conditions.

►Use the switch statement to select one of many blocks of code to be executed.
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
Control Structure in Php- Looping
►Loops in PHP are used to execute the same block of code a specified number of times.

1. for − loops through a block of code a specified number of times.

for (int counter; test counter; increment counter) { code to be executed for each iteration; }

2. while − loops through a block of code if and as long as a specified condition is true.

while (condition is true) { code to be executed; }

3. do...while − loops through a block of code once, and then repeats the loop as long as a special
condition is true.

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

4. foreach − loops through a block of code for each element in an array

foreach ($array as $value) { code to be executed; }


Exercise 1: Basics of PHP

1. Write a PHP program that displays your age from a variable with echo statement.

2. Write a function to check a number is prime or not using if-else conditional structure.

3. Write a PHP program to compute the sum of the prime numbers less than 100 using
do-while loop.
Arrays in PHP
►An array is a data structure that stores one or more similar type of values in a single value.

►The array() function is usually used when you want to create a new array and populate it with more
than one element, all at the same time.

►There are three different kind of arrays:

1. Numeric array − An array with a numeric index. Values are stored and accessed in linear fashion.
 array(value1,value 2, …value n);

2. Associative array − An array with strings as index. This stores element values in association with
key values .  array(“key1”=>’value1” , “key2”=>”value2”…”keyn”=>”valuen”);

3. Multidimensional array − An array containing one or more arrays and values are accessed using
multiple indices.  array( array( ) );
1. Numeric Indexed Array
►are the arrays whose subscript or index is numeric.
►can store numbers, strings and any object but their index will be represented by numbers.
►By default array index starts from zero.
►we use array() function to create array.
►Example: Creating and accessing items of numeric arrays.
<?php
$cars=array(“BMW”,”VOLVO”,”TOYOTA”);
foreach( $cars as $car ) {
echo $car “<br />"; // display all cars in the array
}
echo $car[1] “<br />"; // display car at index 1
?>
2. Associative Array
►are very similar to numeric arrays in term of functionality but they are different in terms of
their index.
►Associative array will have their index as string so that you can establish a strong
association between key and values.
►NB − Don't keep associative array inside double quote while printing otherwise it would not
return any value.
►Example: Creating and accessing items of associative arrays.
<?php
$books=array(“title”=>”PHP Script”, ”author”=>”Abebe”, ”publisher”=>”Mega”);
echo “Book Title: ” . $books[“title”] . “<br />";
echo “Book Author: ” . $books[“author”] . “<br />";
echo “Book Publisher: ” . $books[“publisher”] . “<br />";
}
3. Multidimensional Arrays
►A multi-dimensional 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.
►Values in the multi-dimensional array are accessed using multiple index.
►Example: create a 2D array to store marks of two students in three subjects
<?php
$marks = array( “Girma" => array ("physics" => 35, "maths" => 30, "chemistry" => 39),
“Kalkidan" => array ("physics" => 30, "maths" => 32, "chemistry" => 29));
echo “ Girma’s Physics Mark is: ” . $marks[‘Girma']['physics'] . "<br />";
echo “ Girma’s Maths Mark is: ” . $marks[‘Girma'][‘maths'] . "<br />";
echo “ Kalkidan’s Physics Mark is: ” . $marks[‘Kalkidan']['physics'] . "<br />";
echo “ Kalkidan’s Chemistry Mark is: ” . $marks[‘Kalkidan'][‘chemistry'] . "<br />";
}
Viewing Array Structure and Values
►You can see the structure and values of any array by using one of two statements —
var_dump() or print_r().
►The print_r() statement, however, gives somewhat less information.
►<?php
$cities = array("London", "Paris", "New York");
print_r($cities); // Display: Array ( [0] => London [1] => Paris [2] => New York )
var_dump($cities);
//array(3) { [0]=> string(6) "London" [1]=> string(5) "Paris" [2]=> string(8) "New York" }
} $Book = array( “title” = > “php”, “author”
= > “John”, “pubYear” = > 1939 );
►Looping through array using foreach:
This displays: foreach ( $Book as $k = > $v ) {
foreach ($cities as $val ) { London echo “ key: $k < br > ”;
echo $val . “ < br/ > ”; Paris echo “ value: $v < br > ”;
New York }
Sorting Arrays in PHP
►PHP comes with a number of built-in functions designed specifically for sorting array
elements in different ways like alphabetically or numerically in ascending or descending
order.
►Here are some of the most commonly used functions for sorting arrays:
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
Sorting Arrays in PHP
<?php // Sorting Indexed Array
$colors = array("Red", "Green", "Blue", "Yellow");
sort($colors);
print_r($colors); //Array ( [0] => Blue [1] => Green [2] => Red [3] => Yellow )
rsort($colors);
print_r($colors); //Array ( [0] => Yellow [1] => Red [2] => Green [3] => Blue )
?>
<?php // Sorting Associative Array by value
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
asort($age);
print_r($age);?> //Array ( [Harry] => 14 [Peter] => 20 [Clark] => 35 [John] => 45 )
arsort($age);
print_r($age); //Array ( [John] => 45 [Clark] => 35 [Peter] => 20 [Harry] => 14 )
Sorting Arrays in PHP
<?php // Sorting Associative Array by key
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
ksort($age);
print_r($age); //Array ( [Clark] => 35 [Harry] => 14 [John] => 45 [Peter] => 20 )

krsort($age);
print_r($age); //Array ( [Peter] => 20 [John] => 45 [Harry] => 14 [Clark] => 35 )
?>
►count() and sizeof() –to count number of elements in the array
e.g. echo count($age); // display: 4
echo sizeof($age); // display: 4
Adding and Removing Array Elements
You can add elements to an array using square bracket syntax. For example:
$myArray[] = “new value”; - for indexed array
$myArray[“newKey”] = “new value”; - for associative array
<?php
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
$age[“Joe"]=40; // adds [“Joe”]=>40 new element to $age array
?>
array_unshift(array, value) – Adds one or more new elements to the start of an array
array_shift(array) – Removes the first element from the start of an array
array_push(array, value) — Adds one or more new elements to the end of an array
array_pop(array) — Removes the last element from the end of an array
array_splice(array, from, numofelements-to-remove, new-values) — Removes element(s) from
and/or adds element(s) to any point in an array.
Adding and Removing Array Elements - Examples
<?php
$num = array(12,98,56,40,100);
array_unshift($num, 78);
print_r($num); // Array ( [0] => 78 [1] => 12 [2] => 98 [3] => 56 [4] => 40 [5] => 100 )
array_shift($num);
print_r($num); // Array ( [0] => 12 [1] => 98 [2] => 56 [3] => 40 [4] => 100 )
array_push($num, 25);
print_r($num); //Array ( [0] => 12 [1] => 98 [2] => 56 [3] => 40 [4] => 100 [5] => 25 )
array_pop($num);
print_r($num); //Array ( [0] => 12 [1] => 98 [2] => 56 [3] => 40 [4] => 100 )
?>
Adding and Removing Array Elements - Examples
<?php
$num = array(12,98,56,40,100);
array_splice($num, 1, 0, 245); // adds 245 at index 1 without removing element(0)
print_r($num); //Array ( [0] => 12 [1] => 245 [2] => 98 [3] => 56 [4] => 40 [5] => 100 )
array_splice($num, 3); // removes elements starting from index 3
print_r($num); // Array ( [0] => 12 [1] => 245 [2] => 98 )
array_splice($num, 1, 1, 333); // removes element at index 1 and replace it by 333
print_r($num); //Array ( [0] => 12 [1] => 333 [2] => 98 )
array_splice($num, 1, 2, 333); // removes two elements starting at index 1 and replace by 333
print_r($num); // Array ( [0] => 12 [1] => 333 )
?>
PHP Functions
►A function is a self-contained block of code that performs a specific task.
►It is a way to create reusable code packages that perform specific tasks and can be kept and
maintained separately form main program.
►advantages of using functions:
 Code Reusability: Functions reduces the repetition of code within a program
 Simplicity: Functions makes the code much easier to maintain
 Functions makes it easier to eliminate the errors
 Reusability: Functions can be reused in other application

►Syntax: function functionName(){


//Code to be executed
}
PHP Functions
►Functions in PHP can be:
User-defined functions – are functions that are defined by user.
Built-in functions – are functions that come with php or built into the php. PHP has
over 1000 built-in functions.
User-defined Functions - To define your own PHP functions, you have to follow the
following syntax.
Syntax: function functionName(){
//Code to be executed
}
Note: Function name must start with letter<?php
or underscore only like other labels in PHP. It can't be
start with numbers or special symbols. function sayHello(){
echo "Hello PHP Function";
}
sayHello();//calling function
Example: ?>
PHP Function Arguments
►We can pass the information in PHP function through arguments.
►An argument is just like a variable. Functions execute after they are invoked by writing
their name along with values you wish to assign.
►These values(arguments) are specified after the function name, inside the parentheses.
►You can add as many arguments as you want, just separate them with a comma.
Functions with Parameters Functions calling(passing value)
function myFunc($param1, $param2){
// Code to be executed myFunc(10, 20);
} myFunc(“Hello”, “World”);
►In php we can pass arguments in the following ways:
Pass arguments by Value (default)
Pass arguments by Reference
Default argument values
Passing Arguments by Value(call by value)
►In case of PHP call by value, actual value is not modified if it is modified inside
the function.
►Example:

<?php
function increment($i){
$i++;
echo "Local ".$i; Output:
echo “<br>”;
} Local 11
$i = 10; By value 10
increment($i);
echo "By value ".$i;
?>
Passing Arguments by Reference (call by reference).
►The actual value is modified if it is modified inside the function.
►In such case, you need to use & (ampersand) symbol with formal arguments.
►The & represents reference of the variable.

<?php
function increment(&$i){
$i++;
echo "Local ".$i; Output:
echo “<br>”;
} Local 11
$i = 10; By value 11
increment($i);
echo "By value ".$i;
?>
PHP Default Argument Value
►If we call the function without arguments it takes the default value as argument.
►Means, if you don't pass any value to the function, it will use default argument value.

function add($a=10, $b=20)


{ Output:
$n= $a+$b;
30
echo $n."<br>";
43
}
66
add();
add(23);
add(23,43);
?>

►Note that when using default arguments, any defaults should be on the right side of any
non-default arguments; otherwise, things will not work as expected.
Returning Values from a Function
►uses the return statement to make the function in PHP return a value after successful
execution.
►Any type may be returned, including lists and objects.
►This causes the function to end its execution immediately and pass control back to the line
from which it was called
►Example:
<?php
function getSum($num1, $num2){
$total = $num1 + $num2; Output:
return $total;
} 15
echo getSum(5, 10); // Outputs: 15
?>

You might also like