Chapter-2 Basics of PHP - part-II
Chapter-2 Basics of PHP - part-II
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.
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
2. Pass by reference
3. Return by reference
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;
– 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)
);
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
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
B. Returning Values
A. Functions can also return values using the return statement:
<?php
function add($a, $b) {
return $a + $b;
}