0% found this document useful (0 votes)
97 views33 pages

PHP Programming: Functions, Strings, Arrays, Date and Time: John Ryan B. Lorca Instructor I

The document discusses PHP programming concepts including functions, strings, arrays, and date/time. It provides examples of how to create and use functions with parameters, manipulate strings using methods like strlen() and strpos(), create and modify arrays using array() and square bracket syntax, and format dates using characters like d, F, and N. Exercises are included to create functions that perform math operations and combine arrays in an alternating format.

Uploaded by

Eric Nilo
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
97 views33 pages

PHP Programming: Functions, Strings, Arrays, Date and Time: John Ryan B. Lorca Instructor I

The document discusses PHP programming concepts including functions, strings, arrays, and date/time. It provides examples of how to create and use functions with parameters, manipulate strings using methods like strlen() and strpos(), create and modify arrays using array() and square bracket syntax, and format dates using characters like d, F, and N. Exercises are included to create functions that perform math operations and combine arrays in an alternating format.

Uploaded by

Eric Nilo
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 33

PHP Programming: Functions, Strings, Arrays, Date and Time

John Ryan B. Lorca Instructor I

Functions
A function is a block of code that can be executed whenever we need it. Creating PHP functions:
All functions start with the word "function()" Name the function - It should be possible to understand what the function does by its name. The name can start with a letter or underscore (not a number) Add a "{" - The function code starts after the opening curly brace Insert the function code Add a "}" - The function is finished by a closing curly brace
2

Functions
A simple function that writes my name when it is called:
<html> <body> <?php function writeMyName() { echo "Marcus Oliver Graichen"; } writeMyName(); ?> </body> </html>
3

Functions
Now we will use the function in a PHP script:
<?php function writeMyName() { echo "Marcus Oliver Graichen"; } echo "Hello world!<br />"; echo "My name is "; writeMyName(); echo ".<br />That's right, "; writeMyName(); echo " is my name."; ?>

Functions
The output of the code will be:
Hello world!
My name is Marcus Oliver Graichen. That's right, Marcus Oliver Graichen is my name.

Functions
Our first function writeMyName() is a very simple function. It only writes a static string. To add more functionality to a function, we can add parameters. A parameter is just like a variable. You may have noticed the parentheses (brackets!) after the function name, like: writeMyName(). The parameters are specified inside the parentheses.
6

Functions
The following example will write different first names, but the same last name:
<?php function writeMyName($fname) { echo $fname . " Smith.<br />"; } echo "My name is "; writeMyName("John"); echo "My name is "; writeMyName("Sarah"); echo "My name is "; writeMyName("Smith"); ?>
7

Functions
The output of the code will be:
My name is John smith.
My name is Sarah Smith. My name is Smith Smith.

Functions
The following function has two parameters:
<?php
function writeMyName($fname,$punctuation) { echo $fname . " Smith" . $punctuation . "<br />"; } echo "My name is "; writeMyName("John","."); echo "My name is "; writeMyName("Sarah","!"); echo "My name is "; writeMyName("Smith","..."); ?>

Functions
The output of the code will be:
My name is John Smith. My name is Sarah Smith! My name is Smith Smith...

10

Functions
Functions can also be used to return values.
<html> <body> <?php function add($x,$y) { $total = $x + $y; return $total; } echo "1 + 16 = " . add(1,16); ?> </body> </html>

11

Functions
The output of the code will be:
1 + 16 = 17

12

Exercise
Create a function that:
receives two (2) parameters: x (double) and y (double) Performs the four fundamental operations:
Addition Subtraction Muliplication Division

Displays result in this format: x + y = <result>


13

Strings
String variables are used for values that contains character strings. We are going to look at some of the most common functions and operators used to manipulate strings in PHP. After we create a string we can manipulate it. A string can be used directly in a function or it can be stored in a variable. Below, the PHP script assigns the string "Hello World" to a string variable called $txt:
<?php
$txt = "Hello World"; echo $txt; ?>
14

Strings
The output of the code will be:
Hello World

15

Strings
The Concatenation Operator There is only one string operator in PHP. The concatenation operator (.) is used to put two string values together. To concatenate two variables together, use the dot (.) operator: <?php $txt1 = "Hello World"; $txt2 = "1234"; echo $txt1 . " " . $txt2; ?> If we look at the code above you see that we used the concatenation operator two times. This is because we had to insert a third string. Between the two string variables we added a string with a single character, an empty space, to separate the two variables.

16

Strings
The output of the code will be:
Hello World 1234

17

Strings
Using the strlen() function The strlen() function is used to find the length of a string. Let's find the length of our string "Hello world!": <?php echo strlen("Hello world!"); ?> The output of the code above will be: 12 The length of a string is often used in loops or other functions, when it is important to know when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string)
18

Strings
Using the strpos() function 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. Let's see if we can find the string "world" in our string: <?php echo strpos("Hello world!","world"); ?> The output of the code above will be: 6 As you see the position of the string "world" in our string is position 6. The reason that it is 6, and not 7, is that the first position in the string is 0, and not 1.
19

Arrays
An array in PHP is actually an ordered map. A map is a type that maps values to keys. This type is optimized in several ways, so you can use it as a real array, or a list (vector), hashtable (which is an implementation of a map), dictionary, collection, stack, queue and probably more. Because you can have another PHP array as a value, you can also quite easily simulate trees.
20

Arrays
Specifying with array() An array can be created by the array() language-construct. It takes a certain number of comma-separated key => value pairs. array( [key =>] value , ... ) // key may be an integer or string // value may be any value <?php $arr = array("foo" => "bar", 12 => true); echo $arr["foo"]; // bar echo $arr[12]; // 1

?> A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08"). Floats in key are truncated to integer. There are no different indexed and associative array types in PHP; there is only one array type, which can both contain integer and string indices.
21

Arrays
A value can be of any PHP type. <?php $arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42)); echo $arr["somearray"][6]; // 5 echo $arr["somearray"][13]; // 9 echo $arr["somearray"]["a"]; // 42 ?> If you do not specify a key for a given value, then the maximum of the integer indices is taken, and the new key will be that maximum value + 1. If you specify a key that already has a value assigned to it, that value will be overwritten. <?php // This array is the same as ... array(5 => 43, 32, 56, "b" => 12); // ...this array array(5 => 43, 6 => 32, 7 => 56, "b" => 12); ?>

22

Arrays
Creating/modifying with square-bracket syntax You can also modify an existing array by explicitly setting values in it. This is done by assigning values to the array while specifying the key in brackets. You can also omit the key, add an empty pair of brackets ("[]") to the variable name in that case. $arr[key] = value; $arr[] = value; // key may be an integer or string // value may be any valueIf $arr doesn't exist yet, it will be created. So this is also an alternative way to specify an array. To change a certain value, just assign a new value to an element specified with its key. If you want to remove a key/value pair, you need to unset() it. <?php $arr = array(5 => 1, 12 => 2); $arr[] = 56; // This is the same as $arr[13] = 56; // at this point of the script $arr["x"] = 42; // This adds a new element to // the array with key "x"

unset($arr[5]); // This removes the element from the array


?> unset($arr); // This deletes the whole array

23

Arrays
Note that the maximum integer key used for this need not currently exist in the array. It simply must have existed in the array at some time since the last time the array was re-indexed. The following example illustrates: <?php // Create a simple array. $array = array(1, 2, 3, 4, 5); print_r($array); // Now delete every item, but leave the array itself intact: foreach ($array as $i => $value) { unset($array[$i]); } print_r($array); // Append an item (note that the new key is 5, instead of 0 as you // might expect). $array[] = 6; print_r($array); // Re-index: $array = array_values($array); $array[] = 7; print_r($array); ?>
24

Arrays
Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) Array ( ) Array ( [5] => 6 ) Array ( [0] => 6 [1] => 7 )
25

Exercise
Create two (2) arrays
First Array:
Contains letters from A-J

Second Array:
Contains numbers from 1-10

The result must be a third array containing the values of the first and second array alternatively starting with the first array value Example:
$arr1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} $arr2 = {A, B, C, D, E, F, G, H, I, J} $arr3 = {1, A, 2, B, 3, C, 4, D, 5, E, 6, F, 7, G, 8, H, 9, I, 10, J}

$arr 3 is the result


26

Date and Time


format character Day d D j l (lowercase 'L') Description Example returned values ----Day of the month, 2 digits with 01 to 31 leading zeros A textual representation of a day, Mon through Sun three letters Day of the month without leading 1 to 31 zeros A full textual representation of Sunday through Saturday the day of the week ISO-8601 numeric representation 1 (for Monday) through 7 (for of the day of the week (added in Sunday) PHP 5.1.0) English ordinal suffix for the day st, nd, rd or th. Works well with j of the month, 2 characters Numeric representation of the 0 (for Sunday) through 6 (for day of the week Saturday) The day of the year (starting 27 0 through 365 from 0)

S w z

Date and Time


format character Week W Month F --Description --Example returned values ISO-8601 week number of year, Example: 42 (the 42nd week in the weeks starting on Monday (added in year) PHP 4.1.0) --A full textual representation of a month, such as January or March Numeric representation of a month, with leading zeros A short textual representation of a month, three letters Numeric representation of a month, without leading zeros Number of days in the given month --January through December

01 through 12

Jan through Dec

n t

1 through 12 28 through 31
28

Date and Time


format character Year L --Whether it's a leap year Description --1 if it is a leap year, 0 otherwise. Example returned values

ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) Examples: 1999 or 2003 belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0)

A full numeric representation of Examples: 1999 or 2003 a year, 4 digits

A two digit representation of a year

Examples: 99 or 03

29

Date and Time


format character Time a A B g G h --Lowercase Ante meridiem and Post meridiem Uppercase Ante meridiem and Post meridiem Swatch Internet time 12-hour format of an hour without leading zeros Description --am or pm AM or PM 000 through 999 1 through 12 0 through 23 01 through 12 Example returned values

24-hour format of an hour without leading zeros


12-hour format of an hour with leading zeros

H
i s

24-hour format of an hour with leading zeros


Minutes with leading zeros Seconds, with leading zeros

00 through 23
00 to 59 00 through 59
30

Date and Time


format character Timezone e I (capital i) O Description --Timezone identifier (added in PHP 5.1.0) Whether or not the date is in daylight saving time Difference to Greenwich time (GMT) in hours Example returned values --Examples: UTC, GMT, Atlantic/Azores 1 if Daylight Saving Time, 0 otherwise. Example: +0200

Difference to Greenwich time (GMT) with colon between hours Example: +02:00 and minutes (added in PHP 5.1.3)
Timezone setting of this machine Examples: EST, MDT ... Timezone offset in seconds. The offset for timezones west of UTC -43200 through 43200 is always negative, and for those east of UTC is always positive.

31

Date and Time


format character Full Date/Time c r --Description Example returned values --ISO 8601 date (added in PHP 2004-02-12T15:19:21+00:00 5) RFC 2822 formatted date Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) Example: Thu, 21 Dec 2000 16:01:07 +0200 See also time()

32

Exercise
Produce the following formats:
Today is Sunday, July 26, 2009 Today is the 26th day of July, 2009 July 26, 2009 02:00:00 PM 26 July 2009 02:00 pm 26th of July 2009 2:00 PM 07/26/2009 02:00:00 PM 07-26-2009 02:00 pm 20090726-020000PM
33

You might also like