Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Chapter-2 Basics of PHP - part-II

Chapter 2 of 'Web Design and Development II' focuses on the basics of PHP, covering key topics such as PHP references, arrays, functions, and session and cookies management. It explains the concept of references in PHP, including assign by reference, pass by reference, and return by reference, as well as the different types of arrays: indexed, associative, and multidimensional. The chapter also highlights the advantages of using arrays and provides examples of how to create and manipulate them.

Uploaded by

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

Chapter-2 Basics of PHP - part-II

Chapter 2 of 'Web Design and Development II' focuses on the basics of PHP, covering key topics such as PHP references, arrays, functions, and session and cookies management. It explains the concept of references in PHP, including assign by reference, pass by reference, and return by reference, as well as the different types of arrays: indexed, associative, and multidimensional. The chapter also highlights the advantages of using arrays and provides examples of how to create and manipulate them.

Uploaded by

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

COURSE TITLE:

WEB DESIGN AND DEVELOPMENT II


Chapter- 2
Basics of PHP

By Meresa H.(MSc.)

1
Topics:

1. PHP References
2. Array
3. Function
4. Session and Cookies Management

2
1. PHP References
■ In many ways, PHP is quite different and unique in its own right if we compare it
with other scripting languages such as JavaScript, Python and Ruby.

■ One of those ways in which it's different is that PHP allows us to modify given
entities (variables, array elements, object instances) with the help of other
entities. This is powered by the idea of references in the language.

■ What are references?


– References in PHP are simply a mechanism to get one or more entities to
refer to the exact same content in memory.

– An 'entity' refers to a variable, an array element, or an object instance (more


on that later in the PHP OOP unit).

– In general, it refers to anything that holds a value in PHP.

3
1. PHP References ---(cont’d)
■ There are three kinds of references in PHP:

1. Assign by reference

2. Pass by reference

3. Return by reference

1. Assign by reference(=&) <?php


$a = 5;
– In PHP, you can assign by reference using the & $b = &$a; // $b is a reference to $a
operator. This means that both variables point to
the same memory location, so changes to one echo $a; // Outputs: 5
variable will affect the other. Here's a simple echo $b; // Outputs: 5
example ➔
$b = 10; // Change $b
– In this example, $b is assigned by reference to
$a. When $b is changed, $a is also changed echo $a; // Outputs: 10
because they both refer to the same value. echo $b; // Outputs: 10
?>
4
1. PHP References ---(cont’d)
■ There are three kinds of references in PHP:

2. Pass by reference

– In PHP, you can pass variables by reference to


functions, which allows the function to modify
the original variable. This is done using the &
operator in the function definition.
<?php
– Pass by reference is when we pass arguments to function addFive(&$value) {
$value += 5;
a function via their references. More specifically,
}
we label parameters in the function's definition as
reference parameters. Here's an example: →
$number = 10;
addFive($number);
– In this example, the addFive function takes a
parameter by reference. When the function is echo $number; // Outputs: 15
called with $number, it modifies the original value ?>
of $number
5
1. PHP References ---(cont’d)
■ There are three kinds of references in PHP:

3. Return by reference

– In PHP, you can return a value by reference from a


function using the & operator in the function <?php
declaration. This allows the caller to modify the function &getValue(&$array, $key) {
value of the variable returned by the function. return $array[$key];
}
– The idea is that a function returns a value that is a reference. Then
this value is used to create a second reference, obviously at the time $data = ['a' => 1, 'b' => 2, 'c' => 3];
and site of the function's invocation(call).
$value = &getValue($data, 'b');
– When a function returns a reference, its invocation expression can
be used in the context of assign-by-reference and pass-by- echo $value; // Outputs: 2
reference. Here's an example: →
$value = 10; // Modify the returned
– In this example, the getValue function returns a reference
reference to an element in the $array. When the
returned reference is modified, the original array is echo $data['b']; // Outputs: 10
also updated. ?>
6
2. Array in PHP
■ Arrays are a powerful way to store multiple values in a single variable.
■ An array is assigned to a single variable, but it can hold dozens of
individual pieces of information.
■ Each individual bit of information, or row, is referred to as an array
element.
■ Within every array element there are two parts: the value, which contains
the actual information you want to store, and a unique key which identifies
the value.
■ you will learn later how key palys an importanat role in the process of
accessing and manipulating array elements.
■ Keys can either be non-negative integers or strings.
■ Array with integers as key are the most common type and known as
SCALAR ARRAYS.
■ Those with key as string are known as ASSOCIATIVE ARRAY.

7
2. Array in PHP
■ Advantages of Arrays
– Include a flexible number of list items.
– Can add and delete items on the array.
– Examine each item more concisely.
– You can use looping constructs in combination with arrays to look at
and operate on each array item in a very concise manner.
– Use special array operators (&) and functions.
– Built-in array operators and functions to do things such as
■ count the number of items,
■ sum the items, and
■ sort the array.

8
2. Array in PHP ---(cont’d)
■ There are three types of arrays:
1. Indexed arrays - Arrays with numeric index
2. Associative arrays - Arrays with named keys
3. Multidimensional arrays - Arrays containing one or more arrays
1. Indexed arrays
– Indexed arrays in PHP use numeric indexes to access their elements.
– In an indexed array, each value is assigned a unique index, starting
from zero for the first element and increasing by one for each
subsequent element.
– In index array, you can use in two ways. Here's a simple example:
–You can also create indexed arrays as follows:
<?php
$fruits = array("Apple", "Banana", “Mango"); <?php
echo $fruits[0]; // Outputs: Apple $fruits[0] = “Apple”;
echo $fruits[1]; // Outputs: Banana $fruits[1] = "Banana";
echo $fruits[2]; // Outputs: Mango $fruits[2] = “Mango";
?> ?>
9
2. Array in PHP ---(cont’d)
■ There are three types of arrays:
■ Example-3
1. Indexed arrays Loop Through an Indexed Array
■ Examples1 <?php
<?php $cars=array("Volvo","BMW",
$cars=array("Volvo","BMW","Toyota");
"Toyota"); $arrlength=count($cars);
echo "I like " . $cars[0].", ".$cars[1]."and". $cars[2]. ".";
for($x=0;$x<$arrlength;$x++)
?>
Output is {
➔ I like Volvo, BMW,andToyota. echo $cars[$x];
echo "<br>";
■ Example2 }
Get The Length of an Array – The count() Function used ?>
to return the length of an array: ■ Out put is
<?php
$cars=array("Volvo", "BMW","Toyota");
Volvo
echo count($cars); BMW
?> Toyota
• Out Put is
• ➔3
10
2. Array in PHP ---(cont’d)
2. Associative arrays
■ Associative arrays in PHP use named keys to access their elements, making
them ideal for storing data in a more descriptive way.
■ It refers to an array with strings as an index. Rather than storing element
values in a strict linear index order, this stores them in combination with key
values.
■ Associative arrays in PHP store key value pairs.
– For instance, If you need to store marks earned by a student in different
subjects in an array, a numerically indexed array may not be the right choice.
– A better and more effective option would be to use the names of the subjects
as the keys in your associative list, with their respective marks as the value.
■ In terms of features, associative arrays are very similar to numeric arrays,
but they vary in terms of the index.
– The index of an associative array is a string that allows you to create a
strong link between key and value.

11
2. Array in PHP ---(cont’d)
Example:
2. Associative arrays <?php
/* First method to create an associative array. */
■ A numerically indexed array is not the $student_one = array("Maths"=>95, "Physics"=>90,
best option for storing employee salaries "Chemistry"=>96, "English"=>93,
"Computer"=>98);
in an array. /* Second method to create an associative array. */
$student_two["Maths"] = 97;
■ Instead, you can use the employees' $student_two["Physics"] = 92;
names as keys in an associative list, with $student_two["Chemistry"] = 94;
$student_two["English"] = 96;
their salaries as the value. $student_two["Computer"] = 91;

■ Syntax: /* Accessing the elements directly */


echo "Marks for student one is:<br>";
– “$variable name...” is the variable's echo "Maths:" . $student_one["Maths"], "<br>";
name, “['key name']” is the element's echo "Physics:" . $student_one["Physics"], "<br>";
echo "Chemistry:" . $student_one["Chemistry"], "<br>";
access index number, and “value” is the echo "English:" . $student_one["English"], "<br>";
echo "Computer:" . $student_one["Computer"], "<br>";
array element's value.
echo "Marks for student two is:<br>";
echo "Maths:" . $student_two["Maths"], "<br>";
echo "Physics:" . $student_two["Physics"], "<br>";
echo "Chemistry:" . $student_two["Chemistry"], "<br>";
echo "English:" . $student_two["English"], "<br>";
echo "Computer:" . $student_two["Computer"]; 12
2. Array in PHP ---(cont’d)
2. Associative arrays • List(Vector)
<?php
■ An associative array in PHP represents an $my_array = array("Dog","Cat","Horse");
ordered map. list($a, $b, $c) = $my_array;
echo "I have several animals, a $a, a $b and a $c.";
■ A map is a data form that associates keys ?>
with values. • Hash table
■ This form is well-suited to a variety of • Hash mapping using Tree, and Graphics
tasks; it can be used as • Dictionary
<?php
– an array, → $array1 = array( "item 1" => "one", "item 2" => "two", "item 3" =>
"three", );
– list (vector), → echo $array1["item 1"], ";", $array1["item 2"], ";", $array1["item 3"];
// Output: one;two;three
– a hash table (a map implementation), ?>

– dictionary, → • Set
<?php
– set, → $a = "32"; // string
– stack, → settype($a, "integer"); // $a is now integer
$b = 32; // integer
– queue, and possibly more. settype($b, "string"); // $b is now string
■ Trees and multidimensional associative ?>
arrays in PHP are also possible since array • ETC …..
values may be other arrays.
13
2. Array in PHP ---(cont’d)
2. Associative arrays <?php
/* Creating an associative array */
■ Traversing the Associative Array: $student_one = array("Maths"=>95,
"Physics"=>90,
• We can traverse associative arrays using
"Chemistry"=>96, "English"=>93,
loops. We can loop through the "Computer"=>98);
associative array in two ways. /* Looping through an array using foreach */
echo "Looping using foreach: <br>";
• First by using for loop and secondly by foreach ($student_one as $subject => $marks){
using foreach. echo "Student one got ".$marks." in
".$subject."<br>";
}
/* Looping through an array using for */
echo "\nLooping using for: <br>";
$subject = array_keys($student_one);
$marks = count($student_one);
for($i=0; $i < $marks; ++$i) {
echo $subject[$i] . ' ' .
$student_one[$subject[$i]] . "<br>";
}
?>

14
2. Array in PHP ---(cont’d)
3. Multidimensional arrays
■ Multidimensional arrays in PHP are arrays that contain other arrays as
their elements.
■ It’s also known as array of arrays, which allows you to store tabular data
in an array.
■ They can be used to store data in a more complex structure, such as a
table or a matrix.
■ PHP multidimensional array can be represented in the form of matrix
which is represented by row * column.
<?php
$matrix = array(
array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9)
);
echo $matrix[0][0]; // Outputs: 1
echo $matrix[1][2]; // Outputs: 6
?> 15
2. Array in PHP ---(cont’d)
3. Multidimensional arrays
■ Types of Multidimensional
1. Two-Dimensional Arrays
2. Associative Multidimensional Arrays
3. Looping Through Multidimensional Arrays
1. Two-Dimensional Arrays
■ A two-dimensional array is like a table with rows and columns. Here's an
example: <?php
$matrix = array(
array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9)
);

echo $matrix[0][0],”<br>”; // Outputs: 1


echo $matrix[1][2]; // Outputs: 6
?>

16
2. Array in PHP ---(cont’d)
3. Multidimensional arrays
2. Associative Multidimensional Arrays
– You can also have associative arrays within a multidimensional array.
Here's an example:
<?php
$contacts = array(
"John" => array(
"phone" => "123-456-7890",
"email" => "john@example.com"
),
"Jane" => array(
"phone" => "987-654-3210",
"email" => "jane@example.com"
)
);
echo $contacts["John"]["phone"]; // Outputs: 123-456-7890
?>

17
2. Array in PHP ---(cont’d)
3. Multidimensional arrays
3. Looping Through Multidimensional Arrays
– You can loop through a multidimensional array using nested loops. Here's an
example:
<?php
$matrix = array(
array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9) Output➔1 2 3 4 5 6 7 8 9
);
for ($i = 0; $i < count($matrix); $i++) {
for ($j = 0; $j < count($matrix[$i]); $j++) {
echo $matrix[$i][$j] . " ";
}
echo "\n";
}
?>

18
2. Array in PHP ---(cont’d)
■ Array Functions

function name(s) description


Count() number of elements in the array
print_r() print array's contents
array_pop(), array_push(),
using array as a stack/queue
array_shift(), array_unshift()
in_array(), array_search(), array_reverse(),
searching and reordering
sort(), rsort(), shuffle()
array_fill(), array_merge(), array_intersect(),
creating, filling, filtering
array_diff(), array_slice(), range()
array_sum(), array_product(),
processing elements
array_unique(), array_filter(),array_reduce()

19
3. PHP Function
■ PHP functions are blocks of code that can be repeatedly called to perform
specific tasks.
■ They help in organizing code, making it more readable and reusable.
■ Function can be basically categorized in to two
1. Built-in
2. User Defined
■ Why Functions?
• PHP has lots of built-in functions that we use all the time.
• We write our own functions when our code reaches a certain level of
complexity.

20
3. PHP Function
■ How to create a function,
– Organize your code into “paragraphs” - capture a complete thought and
“name it”.
– Don’t repeat yourself - make it work once and then reuse it.
– If something gets too long or complex, break up logical chunks and put
those chunks in functions.
1. Built-In Functions
– Much of the power of PHP comes from its built-in functions.
– Many are modeled after C string library functions (i.e. strlen()).
echo strrev(" .dlrow olleH");//reverse function Output
echo str_repeat("Hip ", 2);//repeat 2* Hello world.
echo strtoupper("hooray!"); //Change to upper Hip Hip
echo strlen("intro"); // count lenth of character HOORAY!
echo "\n"; 5

21
3. PHP Function
1. Built-In Functions
■ Some common Built-in Functions
– PHP Array Function
– PHP Calendar Function
– PHP class/object Function
– PHP Date/Time Function
– PHP Directory Function
– PHP Error Handling Function
– PHP File System Function
– PHP MySQL Function
– PHP Network Function
– PHP String Function
– PHP ODBC Function
– PHP XML Parsing Function
22
3. PHP Function
1. Built-In Functions
Programming in Multiple Files
■ include() - include content of one file to php file.
– gives warning if file not found and continuing executing script
■ require() - compulsory include the specified file.
– gives fatal error and stops executing script furhter.
• E.g. using Required() function (car2.php)
■ E.g. using include() function (save as car1.php)
<html><body><h1>hello</h1><p> ok</p>
<html><body><h1>hello</h1><p> ok</p>
<?php include('a1.php');?>
<?php include 'vars1.php'; echo "you
<?php include 'a1.txt'; ?>
have $color $car";
</body></html>
?>
<body> <h1>Welcome to my home page!</h1> </body></html>
<?php include 'vars.php'; echo "I have a $color $car."; Eg. <body>
?> <h1>Welcome to my home page!</h1>
</body> <?php require 'vars1.php'; echo "I have a
$color $car.";
<?php ?>
$color='red'; $car='BMW'; </body>
<?php
?> $color='red'; $car='BMW';
?> 23
3. PHP Function

1. Built-In Functions
■ Including Files in PHP

• include "header.php"; - Pull the file in here

• include_once "header.php"; - Pull the file in here unless it has


already been pulled in before

• require "header.php"; - Pull in the file here and die if it is


missing

• require_once "header.php"; - You can guess what this


means...

• These can look like functions - require_once("header.php");


24
3. PHP Function
2. User Defined Functions (Defining Your Own Functions)
■ We use the function keyword to define a function, we name the function
and take optional argument variables.
■ Information to be passed to them & usually return value.
■ Function name are case-insensitive All function require parenthesis
■ The body of the function is in a block of code { }
■ Defining a user-defined function:
function fun_name(arg1,arg2) <?php
function selamta()
{
{
--- echo “Hey, Good Morning";
--- }
} selamta();
SELAMTA(); Out Put
?> Hey, Good Morning
Hey, Good Morning
25
3. PHP Function
2. User Defined Functions
A. Calling a Function
– Once a function is defined, you can call it by using its name followed by
parentheses. If the function requires parameters, you pass them inside the
parentheses: <?php
greet("Alice"); // Outputs: Hello, Alice!
?>

B. Returning Values
A. Functions can also return values using the return statement:

<?php
function add($a, $b) {
return $a + $b;
}

$result = add(5, 3);


echo $result; // Outputs: 8
?> 26
3. PHP Function
2. User Defined Functions
C. Default Parameters
■ You can define default values for parameters, which will be used
if no arguments are provided when the function is called:
<?php
function greet($name = "Guest") {
echo "Hello, $name!";
}
greet(); // Outputs: Hello, Guest!
greet("Alice"); // Outputs: Hello, Alice!
?>
<?php
D. Variable Scope $globalVar = "I am global";
– Variables defined inside a function are local to that function test() {
function and cannot be accessed outside of it. global $globalVar;
– You can use the global keyword to access global echo $globalVar;
variables inside a function: }
test(); // Outputs: I am global
?> 27
28

You might also like