PHP Programming: Functions, Strings, Arrays, Date and Time: John Ryan B. Lorca Instructor I
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
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"
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}
S w z
01 through 12
n t
1 through 12 28 through 31
28
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)
Examples: 99 or 03
29
H
i s
00 through 23
00 to 59 00 through 59
30
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
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