Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Subtopic 1: PHP ARRAYS Arrays - Is Used To Aggregate A Series of Similar Items Together, Arranging and Dereferencing Them in

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 22

MODULE 3

Subtopic 1: PHP ARRAYS

Arrays – is used to aggregate a series of similar items together, arranging and dereferencing them in
some specific way.

 Each member of the array index references a corresponding value and can be a simple
numerical reference to the value’s position in the series, or it could have some direct correlation
to the value.
 PHP array does not need to declare how many elements that the array variable have.
 Array index in PHP can be called as array keys.
 Array can be used as ordinary same as in C and C++ arrays.

Array: one dimensional

Example: Code 1

Example: Code 2

Example: Code 3
Array: Function for visualizing arrays

 print_r () function – short for print recursive. This takes an argument of any type and prints it
out, which includes printing all its parts recursively.
 var_dump() function – is same as the print_r function except that it prints additional
information about the size and type of the values it discovers
- print_r() and var_dump() functions – are commonly used for debugging. The point of these
functions is to help you viualize what’s going on with compound data structures like arrays.

Example: using print_r()

Example: using var_dump()

Array: Looping through array elements

 foreach() function – is a statement used t iterate or loop through the element in an array. With
each loop, a foreach statement moves to the next element in an array.
 foreach statement – specify an array expression within a set of parenthesis following the
foreach keyword.
 Syntax

 $arr – the name of the array that you’re walking through.


 $key – the name of the variable where you want to store the key. (option)
 $value – the name of the variable where you want to store the value
Example:

Example:

Arrays: Multidimensional arrays

Example:

Arrays: Sorting
Funstion Description
sort($array) Sorts by value; assign new numbers as the keys
rsort($array) Sorts by value in reverse order; assign new number as the keys
assort($array) Sorts by value; keeps the same key
arsort($array) Sorts by value in reverse order; keeps the same key
ksort($array) Sorts by key
krsort($array) Sorts by key in reverse order
usort($array, functionname) Sorts by function

Example: Output:

Example: Output:

Subtopic 2: PHP USER DEFINED FUNCTIONS


 Functions – is a group statements that performs a specific task. Functions are designed to allow
you to reuse the same code in different locations.
 User defined functions – functions that are provided by the user of the program.
 Predefined functions – functions that are built-in into PHP to perform some standard
operations.

FUNCTIONS: USER DEFINED FUNCTIONS

 Syntax:
function name(param) {
//code to be executed nu the function
}
 Where
function – is the keyword used to declare a function
name – is the name of he functions or function identifier
param – is the formal parameters of the function. Parameter must follow the rule of naming
identifier.

FUNTIONS: FUNCTION WITH NO PARAMETERS

Example: Output:

FUNCTIONS: FUNCTION WITH PARAMETERS

Example: Output:

FUNCTIONS: FUNCTION THAT RETURNS A VALUE


Example: Output:

FUNCTIONS: NESTED FUNCTION

Example:

Example: Output:

FUNCTIONS: VARIABLE SCOPE

 Global Variables – is one that declared outside a function and is available to all parts of the
program
 Local variables – is declared inside a function and is only available within the function in which it
is declared.
 Static variables – is used to retain the values calls to the same function.

FUNCTIONS: USING VARIABLES


Example: Output:

Example: Output:

Example: Output:

Example: Output:

Example:

SUBTOPIC 1: SUMMARY
 Array is used to aggregate a series of similar items together.
 Array index references a corresponding value.
 Array index can be simple numerical or have some direct correlation to the value.
 Array index is also known as Array Keys.
 print_r function is used to print the array structure.
 var_dump function is same as print_r function except it adds additional information about the
data of each element.
 The foreach statement you can display both the keys and value of each element in the array.
 PHP provided function for array manipulation such as sort(), rsort(), asort(). Arsort(), ksort(), and
usort() functions.
 sort(), asort() and ksort() functions are used to sort elements in the array in ascending order.
 rsort(), arsort(), and ksort() functions are used to sort elements in the array in ascending order.
 sort() and rsort() does not maintain its index reference for each values.
 asort(), ksort(), arsort(), and krsort() maintains its reference for each values.
 asrot() and arsort() used to sort elements by values.
 ksort() and krsort() used to sort elements by keys.

SUBTOPIC 2: SUMMARY

 Functions is a group of PHP statements that performs a specific task.


 Functions can be user defined generally defined by the user of the program and predefined that
are build in using libraries.
 You can function in different ways. Function can only do something without passing values. You
can pass values to a function and you can ask functions to return a value.
 Function keyword is used in PHP to declare a function.
 A function that is declared inside a function is said to be hidden.
 To gain access to a variable that is outside from the function we use the global keyword.
 We use static keyword to declare a variable inside a function that will act as accumulator
variable this will let the program remember the last value of the variable that was used.

CODIO

PHP ARRAY

 Is used to aggregate a series of similar items together, arranging and dereferencing them in
some specific way.
 An array stores multiple value in one single variable.
 PHP array does not need to declare how many elements that the array variable have.

WHAT IS AN ARRAY?

 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”;
 However, what if you want to loop through the cars and find a specific one? 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.

ONE DIMENSIONAL ARRAY

PHP Indexed Arrays

 There are two ways to create indexed arrays:


 The indexed can be assigned automatically (index always starts at 0), like this:
$color = array(“Red”, “Blue”, “Green”)
 Or the index can be assigned manually:
$color[0] = “Red”;
$color[1] = “Blue”;
$color[2] = “Green”;
 The following example creates an indexed array named $cars, assigns three elements to it, and
then prints a text containing the array values:
$color = array(“Red”, “Blue”, “Green”);
echo “I like” .$color[0] . “,” .$color[1] . “and” .$color[2] . “.”
 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:
Example:
$color = array(“Red”, “Blue”, “Green”);
$arrlength = count($color);
for($x = 0; $x < $arrlength; $x++) {
echo $color[$x];
echo “\n”;
}

ARRAY FUNCTIONS

Array Function: print_r

 print_r() function short for print recursive . This takes an argument of any type and prints it out,
which includes printing all its parts recursively.
$fruit = array(“Apple”, “Banana”, “Grapes”, “Orange”);
print_r($fruit);
ARRAY ELEMENTS

PHP Associative Arrays

 Associative arrays are arrays that use named keys that you assign to them.
 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”;
 The named keys cab then be used in a script:
Example:
$age = array(“Peter”=>”35”, “Ben”=> ”37”, “Joe”=> “43”);
echo “Peter is “ .$age[‘Pete’] . “years old.”;

Loop Through an Associative Array

 o loop through and print all the values of an associative array, you could use a foreach loop, like
this:
Example:
$age = array(“Peter”=> “35”, “Ben”=> “37”, “Joe”=> “43”);

foreach($age as $x => $x_value) {


echo “Key=” .$x . “, Value=” . $x_value;
echo ”\n”;
}

MULTI DIMENSIONAL ARRAY

PHP – Multidimensional Arrays

 A multidimensional array is an array containing one or more arrays.


 PHP supports 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

Example:

Name Stock Sold


Volvo 22 18
BMW 15 13
Saab 5 2
Land Rover 17 15
 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):
Output:
echo $cars[0][0].”: In Stock: “.$cars[0][1].”, sold: “.$cars[0][2].”\n”;
echo $cars[1][0].”: In Stock: “.$cars[1][1].”, sold: “.$cars[1][2].”\n”;
echo $cars[2][0].”: In Stock: “.$cars[2][1].”, sold: “.$cars[2][2].”\n”;
echo $cars[3][0].”: In Stock: “.$cars[3][1].”, sold: “.$cars[3][2].”\n”;
 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):
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[$rows][$col]. “</li>”;
}
echo “</ul>”;
}

ARRAY SORTING SORT()

Sort Array in Ascending Order

 sort() – sort arrays in ascending order


 The example sorts the elements of the $number array in ascending numerical order:
$numbers = array(4, 6, 2, 22, 11);
sort($number);
print_r($numbers);

ARRAY SORTING RSORT()

Sort Array in Decending Order

 rsort() – sort arrays in descending order


 The example sorts the elements of the $cars array in descending alphabetical order:
$names = $array(“Aira”, “Rey”, “Joyce”, “Amira”);
rsort($names);
print_r($names);

ARRAY SORTING ARSORT()

Sort Array (Ascending Order), According


 asort() – sort associative arrays in ascending order, according to the value.
 The example sorts an associative array in ascending order, according to the value:
$age = array(“Peter” =>”53”, “Ben”=>”37”, “Joe”=>”43”);
asort($age);
print_r($age);

ARRAY SORTING KSORT()

Sort Array (Ascending Order), According to Key

 ksort() - sort associative arrays in ascending order, according to the key.


 The example sorts an associative array in ascending order, according to the key:
$age = array(“Peter”=>”35”, “Ben=>”37”, “Joe”=>”43”);
ksort($age);
print_r($age);

ARRAY SORTING ARSORT()

Sort Array (Descending Order), According to Value

 arsort() – sort associative arrays in descending order, according to the value


 The example sorts an associative array in descending order, according to the value:
$age = array(“Peter”=>”35”, “Ben”=>”37”, “Joe”=”43”);
arsort($age);
print_r($age);

ARRAY SORTING KSORT()

Sort Array (Descending Order), According to Key

 ksort() – sort associative arrays in descending order, according to the key


 The example sorts an associative array in descending order, according to the key:
$age = array(“Peter”=>”35”, “Ben”=>”37”, “Joe”=>”43”);
ksort($age);
print_r($age);

MODULE 4

Subtopic 1: CONSTRANTS, FILES, AND MATHEMATICAL FUNCTIONS

Using Constant

 define() functions – used to declare constants. A constant can only be assigned a scalar value,
like a string or a number. A constant’s value cannot be changed.
Syntax:
define (‘NAME’, ‘value’);

Example: Output:
Including Files

 You can separate your PHP file and embed it to your html by using PHP include functions.

Include functions Description


include Includes and evaluates the specified file. Generate a warning on failure
message if file not found.
require Performs the same way as the include function. Generate a fatal error
message if file not found stopping the script at that point.
include_once Same as include function except it includes the file only once.
required_once Same as require function except it includes the file only once.
 Most of the developers used include functions for their header and footer. Also some use this to
write their database connection and so on.
 You may write the file with an extension name of .inc rather than .php to serve as a fragment of
your program code.
 In some scripts, a file might be included more than once, causing function redefinitions, variable
reassignments, and other possible problems.
Syntax:
include(“filename.inc”);
include_once(“filename.inc”);
require(“filename.inc”);
require_once(“filename.inc”);

Include Files: include() function (file not found)

Example:

Output:
Including Files: include() function (file not found)

Example:

Output:

Including Files: include() function (file not found)

Example:

Output:

Including Files: include() function (file exists)

Example: header.inc
Output:

Mathematical Function:

 rand() function
- used to generate random integers
- syntax
int rand(void)
int rand(int #min, int $max)
 ceil() function
- returns the next highest integer by rounding the value upwards.
- Syntax
float ceil(float $value)
 floor() function
- returns the next lowest integer by rounding the value downwards.
- Syntax
float floor(float $value)
 min() function
- return the smallest value
- syntax
mixed min(array $values)
mixed min(mixed $values1, mixed $values2[,mixed $...])
 max() function
- return the highest value
- syntax
mixed max(array $values)
mixed max(mixed $values1, mixed $values2[,mixed $...])
Mathematical Function:

rand(), ceil(), floor(), min(), and max()

Example:

 number_format() function
- Format a number with grouped thousand
- Syntax
string number_format (
float $number
[, int $decimals = 0 ] )
string number_format (
float $number ,
int $decimals = 0 ,
string $dec_point = '.' ,
string $thousands_sep = ',' )

Mathematical Function: number_format function

Example: Output:
Subtopic 2: ARRAY, STRING AND DATE MANIPULATION

Function for Array Manipulation:

 unset function
- destroys the specified variable
- syntax:
void unset ( mixed $var [, mixed $... ] )
 explode function
- split a string by string
- syntax
array explode ( string $delimiter ,
string $string [, int $ limit ] )
 implode function
- join array elements to form a string
- syntax
string implode ( string $glue , array $pieces )
string implode ( array $pieces )

unset(), explode(), implode()

Explain: Output:

 strlen function
- return the value length of a string
- syntax
int strlen (string $string)
 strops function
- find the position of the first occurrence of a substring in a given string
- syntax
int strpos ( string $haystack ,
mixed $needle [, int $offset = 0 ] )
 atrrev function
- reverse a given string
- syntax
string strrev ( string $string )
 strtolower function
- converts string to lowercase
- syntax
string strtolower ( string $str )
 strtoupper function
- converts string to uppercase
- syntax
string strtoupper ( string $str )
 substr function
- returns part of a given string
- syntax
string substr ( string $string ,
int $start [, int $length ] )

strlen(), strpe(), strrev(), strtolower(), strtoupper(), substr()

Example:

Output:

 ucfirst() function
- Make a string’s first character uppercase
- Syntax
string ucfirst( string $str )
 Ucwords() function
- converts the first character of each word in a string to uppercase
- syntax
string ucwords ( string $str )
 trim() function
- stripped white spaces or other characters from the beginning and end of a string.
- Syntax
string trim ( string $str [, string $charlist ] )

 ltrim() function
- strip white spaces or other characters from the beginning of a string.
- Syntax
string ltrim ( string $str [, string $charlist ] )
 rtrim() function
- strip white spaces or other characters from the end of a string.
- Syntax
string rtrim ( string $str [, string $charlist ] )
 strip_tags() function
- strip HTML and PHP tags from a string.
- Syntax
string strip_tags ( string $str [, string
$allowable_tags ] )

Ucfirst(), ucwords(), trip(), ltrim(), rtrim(), strip_tags()

Date Manipulation: date() function

 used to format a local time or date


 returns a string formatted according to the given format string
 syntax
string date ( string $format [, int $timestamp = time() ] )

Format Description Example returned values


character
DAY
d Day of the month, 2 digits with leading zeros 01 to 31
D A textual representation of a day, three letters Mon through Sun
j Day of the month without leading zeros 1 to 31
l A full textual representation of the day of the week Sunday through Saturday
N ISO-8601 numeric representation of the day of the 1 (for Monday) through 7 (for
week (added in PHP 5.1.0) Sunday)
S English ordinal suffix for the day of the month, 2 st, nd, rd or th. Works well
characters with j
w Numeric representation of the day of the week 0 (for Sunday) through 6 (for
Saturday)
z The day of the year (starting from 0) 0 through 365
W ISO-8601 week number of year, weeks starting on Example: 42 (the 42nd week in
Monday the year)

Format Description Example returned values


character
MONTH
F A full textual representation of a month, such as January through December
January or March
m Numeric representation of a month, with leading 01 through 12
zeros
M A short textual representation of a month, three Jan through Dec
letters
n Numeric representation of a month, without 1 through 12
leading zeros
t Number of days in the given month 28 through 31

Format Description Example returned values


character
YEAR
L Whether it's a leap year 1 if it is a leap year, 0
otherwise.
o ISO-8601 year number. This has the same value as Examples: 1999 or 2003
Y, except that if the ISO week number (W) belongs
to the previous or next year, that year is used
instead.
Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003
y A two digit representation of a year Examples: 99 or 03

Format Description Example returned values


character
TIME
a Lowercase Ante meridiem and Post meridiem am or pm
A Uppercase Ante meridiem and Post meridiem AM or PM
B Swatch Internet time 000 through 999
g 12-hour format of an hour without leading zeros 1 through 12
G 12-hour format of an hour without leading zeros 0 through 23
h 12-hour format of an hour with leading zeros 01 through 12
H 24-hour format of an hour with leading zeros 00 through 23
i Minutes with leading zeros 00 to 59
s Seconds, with leading zeros 00 through 59
u Microseconds Example: 654321
Format Description Example returned values
character
TIMEZONE
e Timezone identifier Examples: UTC, GMT,
Atlantic/Azores
r Whether or not the date is in daylight saving time 1 if Daylight Saving Time, 0
otherwise.
O Difference to Greenwich time (GMT) in hours Example: +0200
P Difference to Greenwich time (GMT) with colon Example: +02:00
between hours and minutes
T Timezone abbreviation Examples: EST, MDT ...
z Timezone offset in seconds. The offset for -43200 through 50400
timezones west of UTC is always negative, and for
those east of UTC is always positive.

Format Description Example returned values


character
FULL DATE/TIME
c ISO 8601 date 2004-02- 12T15:19:21+00:00
r » RFC 2822 formatted date Example: Thu, 21 Dec 2000
16:01:07 +0200
U Seconds since the Unix Epoch (January 1 1970 See also time()
00:00:00 GMT)

Date Manipulation: date() function

Example: Output:

Date Manipulation: mktime() function

 get the unix timestamp (January 1, 1970) for a given date. (with strict notice)
 same as time() function (without strict notice)
 syntax:
int mktime ([ int $hour = date("H")
[, int $minute = date("i")
[, int $second = date("s")
[, int $month = date("n")
[, int $day = date("j")
[, int $year = date("Y")
[, int $is_dst = -1 ]]]]]]] )

Date Manipulation: strtotime() function

 parse any English textual datetime description into a Unix timestamp


 syntax:
int strtotime ( string $time
[, int $now = time() ] )

You might also like