PHP Mod5
PHP Mod5
Name Description
The default timezone
date.timezone
(used by all date/time functions)
The default latitude
date.default_latitude
(used by date_sunrise() and date_sunset())
The default longitude
date.default_longitude
(used by date_sunrise() and date_sunset())
The default sunrise zenith
date.sunrise_zenith
(used by date_sunrise() and date_sunset())
The default sunset zenith
date.sunset_zenith
(used by date_sunrise() and date_sunset())
Function Description
Validates a
checkdate()
Gregorian date
Adds days, months,
years, hours,
date_add()
minutes, and
seconds to a date
Returns a new
date_create_from_format()
DateTime object
formatted according
to a specified format
Returns a new
date_create()
DateTime object
date_date_set() Sets a new date
Returns the default
date_default_timezone_get() timezone used by all
date/time functions
Sets the default
date_default_timezone_set() timezone used by all
date/time functions
Returns the
date_diff() difference between
two dates
Returns a date
date_format() formatted according
to a specified format
Returns the
warnings/errors
date_get_last_errors()
found in a date
string
Sets up a
DateInterval from
date_interval_create_from_date_string()
the relative parts of
the string
date_interval_format() Formats the interval
date_isodate_set() Sets the ISO date
Modifies the
date_modify()
timestamp
Returns the
date_offset_get()
timezone offset
Returns an
associative array
with detailed info
date_parse_from_format()
about a specified
date, according to a
specified format
Returns an
associative array
date_parse() with detailed info
about a specified
date
Subtracts days,
months, years,
date_sub()
hours, minutes, and
seconds from a date
Returns an array
containing info
about sunset/sunrise
date_sun_info() and twilight
begin/end, for a
specified day and
location
Returns the sunrise
date_sunrise() time for a specified
day and location
Returns the sunset
date_sunset() time for a specified
day and location
date_time_set() Sets the time
Returns the Unix
date_timestamp_get()
timestamp
Sets the date and
date_timestamp_set() time based on a
Unix timestamp
Returns the time
date_timezone_get() zone of the given
DateTime object
Sets the time zone
date_timezone_set() for the DateTime
object
Formats a local date
date()
and time
Returns date/time
information of a
getdate() timestamp or the
current local
date/time
Returns the current
gettimeofday()
time
Formats a
gmdate() GMT/UTC date and
time
Returns the Unix
gmmktime() timestamp for a
GMT date
Formats a
GMT/UTC date and
gmstrftime()
time according to
locale settings
Formats a local
idate()
time/date as integer
Returns the local
localtime()
time
Returns the current
microtime() Unix timestamp
with microseconds
Returns the Unix
mktime()
timestamp for a date
Formats a local time
and/or date
strftime()
according to locale
settings
Parses a time/date
strptime() generated with
strftime()
Parses an English
strtotime() textual datetime into
a Unix timestamp
Returns the current
time() time as a Unix
timestamp
Returns an
associative array
timezone_abbreviations_list() containing dst,
offset, and the
timezone name
Returns an indexed
timezone_identifiers_list() array with all
timezone identifiers
Returns location
timezone_location_get() information for a
specified timezone
Returns the
timezone_name_from_ abbr() timezone name from
abbreviation
Returns the name of
timezone_name_get()
the timezone
Returns the
timezone_offset_get() timezone offset
from GMT
Creates new
timezone_open() DateTimeZone
object
Returns all
timezone_transitions_get() transitions for the
timezone
Returns the version
timezone_version_get()
of the timezonedb
Constant Description
Atom (example: 2019-01-
DATE_ATOM
18T14:13:03+00:00)
HTTP Cookies (example: Fri, 18
DATE_COOKIE
Jan 2019 14:13:03 UTC)
ISO-8601 (example: 2019-01-
DATE_ISO8601
18T14:13:03+0000)
RFC 822 (example: Fri, 18 Jan
DATE_RFC822
2019 14:13:03 +0000)
RFC 850 (example: Friday, 18-Jan-
DATE_RFC850
19 14:13:03 UTC)
RFC 1036 (example: Friday, 18-
DATE_RFC1036
Jan-19 14:13:03 +0000)
RFC 1123 (example: Fri, 18 Jan
DATE_RFC1123
2019 14:13:03 +0000)
RFC 2822 (example: Fri, 18 Jan
DATE_RFC2822
2019 14:13:03 +0000)
Same as DATE_ATOM (since PHP
DATE_RFC3339
5.1.3)
RFC3339 Extended format (since
DATE_RFC3339
PHP 7.0.0) (example: 2019-01-
_EXTENDED
18T16:34:01.000+00:00)
RSS (Fri, 18 Jan 2019 14:13:03
DATE_RSS
+0000)
World Wide Web Consortium
DATE_W3C (example: 2019-01-
18T14:13:03+00:00)
SUNFUNCS_RE
Timestamp (since PHP 5.1.2)
T_TIMESTAMP
SUNFUNCS_RE Hours:minutes (example: 09:41)
T_STRING (since PHP 5.1.2)
SUNFUNCS_RE Hours as a floating point number
T_DOUBLE (example: 9.75) (since PHP 5.1.2)
Function Description
Returns a string with backslashes in
addcslashes()
front of the specified characters
Returns a string with backslashes in
addslashes()
front of predefined characters
Converts a string of ASCII characters
bin2hex()
to hexadecimal values
Removes whitespace or other
chop() characters from the right end of a
string
Returns a character from a specified
chr()
ASCII value
Splits a string into a series of smaller
chunk_split()
parts
convert_cyr_str Converts a string from one Cyrillic
ing() character-set to another
convert_uudeco
Decodes a uuencoded string
de()
convert_uuenco Encodes a string using the uuencode
de() algorithm
Returns information about characters
count_chars()
used in a string
crc32() Calculates a 32-bit CRC for a string
crypt() One-way string hashing
echo() Outputs one or more strings
explode() Breaks a string into an array
Writes a formatted string to a
fprintf()
specified output stream
get_html_transl Returns the translation table used by
ation_table() htmlspecialchars() and htmlentities()
hebrev() Converts Hebrew text to visual text
Converts Hebrew text to visual text
hebrevc()
and new lines (\n) into <br>
Converts a string of hexadecimal
hex2bin()
values to ASCII characters
html_entity_de
Converts HTML entities to characters
code()
htmlentities() Converts characters to HTML entities
htmlspecialchar Converts some predefined HTML
s_decode() entities to characters
htmlspecialchar Converts some predefined characters
s() to HTML entities
Returns a string from the elements of
implode()
an array
join() Alias of implode()
Converts the first character of a string
lcfirst()
to lowercase
Returns the Levenshtein distance
levenshtein()
between two strings
Returns locale numeric and monetary
localeconv()
formatting information
Removes whitespace or other
ltrim()
characters from the left side of a string
md5() Calculates the MD5 hash of a string
md5_file() Calculates the MD5 hash of a file
Calculates the metaphone key of a
metaphone()
string
money_format( Returns a string formatted as a
) currency string
nl_langinfo() Returns specific local information
Inserts HTML line breaks in front of
nl2br()
each newline in a string
number_format Formats a number with grouped
() thousands
Returns the ASCII value of the first
ord()
character of a string
parse_str() Parses a query string into variables
print() Outputs one or more strings
printf() Outputs a formatted string
quoted_printabl Converts a quoted-printable string to
e_decode() an 8-bit string
quoted_printabl Converts an 8-bit string to a quoted
e_encode() printable string
quotemeta() Quotes meta characters
Removes whitespace or other
rtrim() characters from the right side of a
string
setlocale() Sets locale information
sha1() Calculates the SHA-1 hash of a string
sha1_file() Calculates the SHA-1 hash of a file
Calculates the similarity between two
similar_text()
strings
soundex() Calculates the soundex key of a string
sprintf() Writes a formatted string to a variable
Parses input from a string according to
sscanf()
a format
str_getcsv() Parses a CSV string into an array
Replaces some characters in a string
str_ireplace()
(case-insensitive)
str_pad() Pads a string to a new length
Repeats a string a specified number of
str_repeat()
times
Replaces some characters in a string
str_replace()
(case-sensitive)
Performs the ROT13 encoding on a
str_rot13()
string
Randomly shuffles all characters in a
str_shuffle()
string
str_split() Splits a string into an array
str_word_count
Count the number of words in a string
()
Compares two strings (case-
strcasecmp()
insensitive)
Finds the first occurrence of a string
strchr()
inside another string (alias of strstr())
strcmp() Compares two strings (case-sensitive)
Compares two strings (locale based
strcoll()
string comparison)
Returns the number of characters
strcspn() found in a string before any part of
some specified characters are found
Strips HTML and PHP tags from a
strip_tags()
string
Unquotes a string quoted with
stripcslashes()
addcslashes()
Unquotes a string quoted with
stripslashes()
addslashes()
Returns the position of the first
stripos() occurrence of a string inside another
string (case-insensitive)
Finds the first occurrence of a string
stristr()
inside another string (case-insensitive)
strlen() Returns the length of a string
Compares two strings using a "natural
strnatcasecmp()
order" algorithm (case-insensitive)
Compares two strings using a "natural
strnatcmp()
order" algorithm (case-sensitive)
String comparison of the first n
strncasecmp()
characters (case-insensitive)
String comparison of the first n
strncmp()
characters (case-sensitive)
Searches a string for any of a set of
strpbrk()
characters
Returns the position of the first
strpos() occurrence of a string inside another
string (case-sensitive)
Finds the last occurrence of a string
strrchr()
inside another string
strrev() Reverses a string
Finds the position of the last
strripos() occurrence of a string inside another
string (case-insensitive)
Finds the position of the last
strrpos() occurrence of a string inside another
string (case-sensitive)
Returns the number of characters
strspn() found in a string that contains only
characters from a specified charlist
Finds the first occurrence of a string
strstr()
inside another string (case-sensitive)
strtok() Splits a string into smaller strings
strtolower() Converts a string to lowercase letters
strtoupper() Converts a string to uppercase letters
Translates certain characters in a
strtr()
string
substr() Returns a part of a string
Compares two strings from a specified
substr_compare
start position (binary safe and
()
optionally case-sensitive)
Counts the number of times a
substr_count()
substring occurs in a string
Replaces a part of a string with
substr_replace()
another string
Removes whitespace or other
trim()
characters from both sides of a string
Converts the first character of a string
ucfirst()
to uppercase
Converts the first character of each
ucwords()
word in a string to uppercase
Writes a formatted string to a
vfprintf()
specified output stream
vprintf() Outputs a formatted string
vsprintf() Writes a formatted string to a variable
Wraps a string to a given number of
wordwrap()
characters
ARRAY FUNCTIONS
array_chunk
Syntax
array array_chunk ( array $input , int $size [, bool
$preserve_keys = false ] )
Description
Chunks an array into size large chunks. The last chunk
may contain less than size elements.
Example
<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
print_r(array_chunk($input_array, 2, true));
?>
Output
Array ( [0] => Array
– ( [0] => a
– [1] => b )
print_r($result);
?>
Output:
• Array ( [1] => blue )
array_intersect
• — Computes the intersection of arrays
Description
• array array_intersect ( array $array1 , array
$array2 [, array $ ... ] )
• array_intersect() returns an array containing
all the values of array1 that are present in all
the arguments. Note that keys are preserved.
• <?php
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red"
);
$result = array_intersect($array1, $array2);
print_r($result);
?>
• The above example will output:
• Array ( [a] => green [0] => red )
array_merge
• — Merge one or more arrays
Description
• array array_merge ( array $array1 [, array $... ] )
• Merges the elements of one or more arrays together so
that the values of one are appended to the end of the
previous one. It returns the resulting array.
• If the input arrays have the same string keys, then the later
value for that key will overwrite the previous one. If,
however, the arrays contain numeric keys, the later value
will not overwrite the original value, but will be appended.
• Values in the input array with numeric keys will be
renumbered with incrementing keys starting from zero in
the result array.
• <?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>
output:
Array (
[color] => green
[0] => 2
[1] => 4
[2] => a
[3] => b
[shape] => trapezoid
[4] => 4 )
array_pop
• — Pop the element off the end of array
• Description
• mixed array_pop ( array &$array )
• array_pop() pops and returns the last value of
the array, shortening the array by one
element. If array is empty (or is not an array),
NULL will be returned. Will additionally
produce a Warning when called on a non-
array.
• <?php
$stack = array("orange", "banana", "apple", "raspberry
");
$fruit = array_pop($stack);
print_r($stack);
?>
After this, $stack will have only 3 elements:
Array (
[0] => orange
[1] => banana
[2] => apple )
array_push
• — Push one or more elements onto the end of array
Description
• int array_push ( array &$array , mixed $var [, mixed $...
])
• array_push() treats array as a stack, and pushes the
passed variables onto the end of array. The length of
array increases by the number of variables pushed. Has
the same effect as:
• <?php
$array[] = $var;
?>
• <?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
?>
• The above example will output:
Array (
[0] => orange
[1] => banana
[2] => apple
[3] => raspberry )
array_replace
• — Replaces elements from passed arrays into the first array
Description
• array array_replace ( array &$array , array &$array1 [, array &$... ] )
• array_replace() replaces the values of the first array with the same
values from all the following arrays. If a key from the first array
exists in the second array, its value will be replaced by the value
from the second array. If the key exists in the second array, and not
the first, it will be created in the first array. If a key only exists in the
first array, it will be left as is. If several arrays are passed for
replacement, they will be processed in order, the later arrays
overwriting the previous values.
• array_replace() is not recursive : it will replace values in the first
array by whatever type is in the second array.
• <?php
$base = array("orange", "banana", "apple", "raspberry");
$replacements = array(0 => "pineapple", 4 => "cherry");
$replacements2 = array(0 => "grape");
$basket = array_replace($base, $replacements, $replacements2);
print_r($basket);
?>
• The above example will output:
Array (
[0] => grape
[1] => banana
[2] => apple
[3] => raspberry
[4] => cherry )
array_reverse
• — Return an array with elements in reverse
order
Description
• array array_reverse ( array $array [, bool
$preserve_keys = false ] )
• Takes an input array and returns a new array
with the order of the elements reversed.
• <?php
$input = array("php", 4.0, array("green", "red"));
$result = array_reverse($input);
$result_keyed = array_reverse($input, true);
?>
Output
Array (
[0] => Array (
[0] => green
[1] => red )
[1] => 4
[2] => php )
Array (
[2] => Array (
[0] => green
[1] => red )
[1] => 4
[0] => php )
array_search
• — Searches the array for a given value and
returns the corresponding key if successful
Description
• mixed array_search ( mixed $needle , array
$haystack [, bool $strict = false ] )
• <?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'gree
n', 3 => 'red');
function function_name()
{
statements;
}
Note: the name of function must start with a letter or underscore not a
number.
Example:
<html>
<body>
<?php
//defining function:printHello
function printHello()
{
echo "Hello";
}
//calling the function:printHello
printHello();
?>
</body>
</html>
function function_name()
{
statements;
return value;
}
Example:
<html>
<body>
<?php
//defining function: sum
function sum(){
$s=10+20;
return $s;
}
//calling the function: sum
$total=sum();
echo "Total=".$total;
?>
</body>
</html>
Function parameters
Parameters are values to be passed to the function. In the example below,
a person' name is passed tothe printName function. You can pass more
than one parameter to the function by separating them with comma.
Example:
<html>
<body>
<?php
//defining function:printName
function printName($name)
{
echo "Hello ".$name;
}
//calling the function:printName
printName("Khorn Channa");
?>
</body>
</html>
PHP - GET & POST Methods
There are two ways the browser client can send information to the web server.
exit();
}
?>
<html>
<body>
</body>
</html>
It will produce the following result −
exit();
}
?>
<html>
<body>
</body>
</html>
It will produce the following result −
The $_REQUEST variable
The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and
$_COOKIE. We will discuss $_COOKIE variable when we will explain about cookies.
The PHP $_REQUEST variable can be used to get the result from form data sent
with both the GET and POST methods.
Try out following example by putting the source code in test.php script.
<?php
if( $_REQUEST["name"] || $_REQUEST["age"] ) {
echo "Welcome ". $_REQUEST['name']. "<br />";
echo "You are ". $_REQUEST['age']. " years old.";
exit();
}
?>
<html>
<body>
</body>
</html>
Here $_PHP_SELF variable contains the name of self script in which it is being called.
It will produce the following result −
PHP FORM INTROUCTION
Example
Below example shows the form with some specific actions by using post method.
<html>
<head>
<title>PHP Form Validation</title>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>classes registration</h2>
<tr>
<td>E-mail:</td>
<td><input type = "text" name = "email"></td>
</tr>
<tr>
<td>Specific Time:</td>
<td><input type = "text" name = "website"></td>
</tr>
<tr>
<td>Class details:</td>
<td><textarea name = "comment" rows = "5" cols =
"40"></textarea></td>
</tr>
<tr>
<td>Gender:</td>
<td>
<input type = "radio" name = "gender" value =
"female">Female
<input type = "radio" name = "gender" value =
"male">Male
</td>
</tr>
<tr>
<td>
<input type = "submit" name = "submit" value =
"Submit">
</td>
</tr>
</table>
</form>
<?php
echo "<h2>Your Given details are as :</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
PHP String Built-in
Functions
Introduction to String Functions
• String functions are essential in PHP for manipulating and
processing text. PHP provides a wide range of built-in string
functions.
• Example:
• $str = 'Hello World';
• echo strlen($str); // Outputs: 11
str_replace() - Replace Substring
• The str_replace() function replaces all occurrences
of a substring with another substring.
• Example:
• $text = 'I love PHP';
• $newText = str_replace('PHP', 'coding', $text);
• echo $newText; // Outputs: 'I love coding'
strpos() - Find Position of
Substring
• The strpos() function finds the position of the first
occurrence of a substring in a string.
• Example:
• $text = 'Hello World';
• $pos = strpos($text, 'World');
• echo $pos; // Outputs: 6 (position of 'World' starts
at index 6)
substr() - Extract a Part of a String
• The substr() function returns a part of a string
starting at a specified position.
• Example:
• $text = 'Hello World';
• $part = substr($text, 6, 5);
• echo $part; // Outputs: 'World' (5 characters
starting from position 6)
strtoupper() and strtolower() -
Change Case
• The strtoupper() function converts a string to
uppercase.
• The strtolower() function converts a string to
lowercase.
• Example:
• $text = 'Hello World';
• echo strtoupper($text); // Outputs: 'HELLO
WORLD'
• echo strtolower($text); // Outputs: 'hello world'
Conclusion
• PHP provides a wide range of built-in string
functions that simplify text manipulation.
• These functions are efficient and useful for various
real-world applications.
• By mastering these functions, you can handle
strings effectively in your PHP projects.
strtolower()
• Converts a string to lowercase.
• Example:
• $text = 'HELLO WORLD';
• echo strtolower($text); // Outputs: 'hello world'
strtoupper()
• Converts a string to uppercase.
• Example:
• $text = 'hello world';
• echo strtoupper($text); // Outputs: 'HELLO
WORLD'
ucfirst()
• Capitalizes the first character of a string.
• Example:
• $text = 'hello world';
• echo ucfirst($text); // Outputs: 'Hello world'
lcfirst()
• Converts the first character of a string to lowercase.
• Example:
• $text = 'Hello World';
• echo lcfirst($text); // Outputs: 'hello World'
ucwords()
• Capitalizes the first character of each word.
• Example:
• $text = 'hello world';
• echo ucwords($text); // Outputs: 'Hello World'
strrev()
• Reverses a string.
• Example:
• $text = 'hello';
• echo strrev($text); // Outputs: 'olleh'
strlen()
• Returns the length of a string.
• Example:
• $text = 'hello';
• echo strlen($text); // Outputs: 5
str_replace()
• Replaces part of a string with another string.
• Example:
• $text = 'I love PHP';
• $newText = str_replace('PHP', 'coding', $text);
• echo $newText; // Outputs: 'I love coding'
explode()
• Splits a string into an array by a delimiter.
• Example:
• $text = 'apple,banana,cherry';
• $fruits = explode(',', $text);
• print_r($fruits); // Outputs: Array([0] => apple, [1]
=> banana, [2] => cherry)
implode()
• Joins array elements into a string.
• Example:
• $fruits = ['apple', 'banana', 'cherry'];
• $text = implode(',', $fruits);
• echo $text; // Outputs: 'apple,banana,cherry'
substr()
• Extracts a substring from a string.
• Example:
• $text = 'Hello World';
• echo substr($text, 6, 5); // Outputs: 'World'
trim()
• Removes whitespace from the start and end of a
string.
• Example:
• $text = ' Hello World ';
• echo trim($text); // Outputs: 'Hello World'
ltrim()
• Removes whitespace from the beginning of a
string.
• Example:
• $text = ' Hello World';
• echo ltrim($text); // Outputs: 'Hello World'
rtrim()
• Removes whitespace from the end of a string.
• Example:
• $text = 'Hello World ';
• echo rtrim($text); // Outputs: 'Hello World'
str_split()
• Splits a string into an array by a specific length.
• Example:
• $text = 'hello';
• $chars = str_split($text, 2);
• print_r($chars); // Outputs: Array([0] => 'he', [1] =>
'll', [2] => 'o')
Modern Web Applications
Module : 5
PHP SERVER SIDE BASICS
http://server/path/file
• Usually when you type a URL in your browser:
• Your computer looks up the server's IP address using DNS
• Your browser connects to that IP address and requests the given file
• The web server software (e.g. Apache) grabs that file from the server's local file
system
• The server sends back its contents to you
2
URLs and web servers (cont.)
Apache, Websphere
SW(Java Servlets,
XML Files)
3
URLs and web servers (cont.)
http://www.facebook.com/home.php
• Some URLs actually specify programs that the web
server should run, and then send their output back to
you as the result:
4
Server-Side web programming
• Server-side pages are programs written using one of
many web programming languages/frameworks
5
Server-Side web programming
(cont.)
6
Server-Side web
programming (cont.)
• Web server:
• contains software that allows it to run server side
programs
• sends back their output as responses to web requests
7
What is PHP?
Hello.php
Hello world!
•Simple
10
Hello World!
<?php
print "Hello, world!";
?> PHP
Hello world!
output
11
Viewing PHP output
Hello world!
12
PHP Basic Syntax
13
PHP syntax template
HTML content
<?php
PHP code
?>
HTML content
<?php
PHP code
?>
HTML content ... PHP
Hello world! Escape "chars" are the SAME as in Java! You can have line
breaks in a string. A string can use "single-quotes". It's cool!
output
15
Variables
$name = expression; PHP
$user_name = “ram80";
$age = 16;
$drinking_age = $age + 5;
$this_class_rocks = TRUE; PHP
18
Comments
# single-line comment
// single-line comment
/*
multi-line comment
*/ PHP
19
PHP Data Types
Overview of String, Integer, Float, Boolean, Array, Object, NULL, and
Resource Data Types
String Data Type
<?php
$string_var = "Hello, World!";
echo $string_var;
?>
Integer Data Type
<?php
$int_var = 42;
echo $int_var;
?>
Float Data Type
<?php
$float_var = 3.14;
echo $float_var;
?>
Boolean Data Type
<?php
$bool_var = true;
echo $bool_var;
?>
Array Data Type
<?php
$array_var = array("apple", "banana", "cherry");
echo $array_var[0];
?>
Object Data Type
<?php
class Car {
public $color;
public function __construct($color) {
$this->color = $color;
}
public function get_color() {
return $this->color;
}
}
$my_car = new Car("red");
echo $my_car->get_color();
?>
NULL Data Type
<?php
$null_var = NULL;
echo $null_var;
?>
Resource Data Type
<?php
$file = fopen("example.txt", "r");
echo fread($file, filesize("example.txt"));
fclose($file);
?>
Change Data Type
Casting in PHP is done with these statements:
(string) - Converts to data type String
(int) - Converts to data type Integer
(float) - Converts to data type Float
(bool) - Converts to data type Boolean
(array) - Converts to data type Array
(object) - Converts to data type Object
(unset) - Converts to data type NULL
29
String Type
$favorite_food = "Ethiopian";
print $favorite_food[2];
$favorite_food = $favorite_food . " cuisine";
print $favorite_food;
PHP
31
String Functions (cont.)
32
Interpreted Strings
$age = 16;
print "You are " . $age . " years old.\n";
print "You are $age years old.\n"; # You are 16 years old.
PHP
33
Interpreted Strings (cont.)
print "Today is your $ageth birthday.\n"; # $ageth not
found
print "Today is your {$age}th birthday.\n";
PHP
34
Interpreted Strings (cont.)
$name = “Xenia";
$name = NULL;
if (isset($name)) {
print "This line isn't going to be reached.\n";
} PHP
a variable is NULL if
it has not been set to any value (undefined variables)
it has been assigned the constant NULL
36
bool (Boolean) type
$feels_like_summer = FALSE;
$php_is_great = TRUE;
$student_count = 7;
$nonzero = (bool) $student_count; # TRUE
PHP
the following values are considered to be FALSE (all
others are TRUE):
0 and 0.0 (but NOT 0.00 or 0.000)
"", "0", and NULL (includes unset variables)
38
while loop (same as Java)
while (condition) {
statements;
} PHP
do {
statements;
} while (condition);
PHP
39
Math operations
$a = 3;
$b = 4;
$c = sqrt(pow($a, 2) + pow($b, 2));
PHP
math functions
40
Int and Float Types
$a = 7 / 2; # float: 3.5
$b = (int) $a; # int: 3
$c = round($a); # float: 4.0
$d = "123"; # string: "123"
$e = (int) $d; # int: 123 PHP
41
Module : 5
PHP Arrays - Functions
2
Arrays
$name = array(); # create
$name = array(value0, value1, ..., valueN);
$name[index] # get element value
$name[index] = value; # set element value
$name[] = value; # append PHP
3
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,
array_unique, processing elements
4
array_filter, array_reduce
Array function example
$tas = array("MD", "BH", "KK", "HM", "JP");
for ($i = 0; $i < count($tas); $i++) {
$tas[$i] = strtolower($tas[$i]);
}
$morgan = array_shift($tas);
array_pop($tas);
array_push($tas, "ms");
array_reverse($tas);
sort($tas);
$best = array_slice($tas, 1, 2);
PHP
5
foreach loop
foreach ($array as $variableName) {
...
} PHP
6
Multidimensional Arrays
<?php $AmazonProducts = array( array(“BOOK",
"Books", 50),
array("DVDs",
“Movies", 15),
array(“CDs", “Music",
20)
);
for ($row = 0; $row < 3; $row++) {
for ($column = 0; $column < 3; $column++) { ?>
<p> | <?=
$AmazonProducts[$row][$column] ?>
<?php } ?>
</p>
<?php } ?>
PHP
7
Multidimensional Arrays (cont.)
<?php $AmazonProducts = array( array(“Code” =>“BOOK",
“Description” => "Books", “Price” => 50),
array(“Code” => "DVDs",
“Description” => “Movies", “Price” => 15),
array(“Code” => “CDs",
“Description” => “Music", “Price” => 20)
);
for ($row = 0; $row < 3; $row++) { ?>
<p> | <?= $AmazonProducts[$row][“Code”] ?> | <?=
$AmazonProducts[$row][“Description”] ?> | <?=
$AmazonProducts[$row][“Price”] ?>
</p>
<?php } ?>
PHP
8
String compare functions
Name Function
strcmp compareTo
strstr, strchr find string/char within a string
find numerical position of
strpos
string
str_replace, substr_replace
• Comparison can be:
replace string
• Partial matches
• Others
• Variations with non case sensitive functions
• strcasecmp
9
String compare functions examples
$offensive = array( offensive word1, offensive
word2);
$feedback = str_replace($offcolor, “%!@*”,
$feedback);
PHP
$toaddress = “[email protected]”;
if(strstr($feedback, “shop”)
$toaddress = “[email protected]”;
else if(strstr($feedback, “delivery”)
$toaddress = “[email protected]”;
PHP
10
Regular expressions
[a-z]at #cat, rat, bat…
[aeiou]
[a-zA-Z]
[^a-z] #not a-z
[[:alnum:]]+ #at least one alphanumeric char
(very) *large #large, very very very large…
(very){1, 3} #counting “very” up to 3
^bob #bob at the beginning
com$ #com at the end PHPRegExp
• Regular expression: a pattern in a piece of text
• PHP has:
• POSIX
• Perl regular expressions
11
Printing HTML tags in PHP = bad style
<?php
print "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML
1.1//EN\"\n";
print "
\"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n";
print "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
print " <head>\n";
print " <title>Geneva's web page</title>\n";
...
for ($i = 1; $i <= 10; $i++) {
print "<p> I can count to $i! </p>\n";
}
?> HTML
• best PHP style is to minimize print/echo statements in embedded
PHP code
• but without print, how do we insert dynamic content into the page?
12
PHP expression blocks
<?= expression ?> PHP
The answer is 42
output
13
Expression block example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>CSE 190 M: Embedded PHP</title></head>
<body>
<?php
for ($i = 99; $i >= 1; $i--) {
?>
<p> <?= $i ?> bottles of beer on the wall, <br />
<?= $i ?> bottles of beer. <br />
Take one down, pass it around, <br />
<?= $i - 1 ?> bottles of beer on the wall. </p>
<?php
}
?>
</body>
</html> PHP14
Common errors: unclosed braces, missing =
sign
...
<body>
<p>Watch how high I can count:
<?php
for ($i = 1; $i <= 10; $i++) {
?>
<? $i ?>
</p>
</body>
</html> PHP
• if you forget to close your braces, you'll see an error about
'unexpected $end'
• if you forget = in <?=, the expression does not produce any output
15
Complex expression blocks
...
<body>
<?php
for ($i = 1; $i <= 3; $i++) {
?>
<h<?= $i ?>>This is a level <?= $i ?>
heading.</h<?= $i ?>>
<?php
}
?>
</body> PHP
16
Functions
function name(parameterName, ..., parameterName) {
statements;
} PHP
17
Default Parameter Values
function print_separated($str, $separator = ", ") {
if (strlen($str) > 0) {
print $str[0];
for ($i = 1; $i < strlen($str); $i++) {
print $separator . $str[$i];
}
}
} PHP
print_separated("hello"); # h, e, l, l, o
print_separated("hello", "-"); # h-e-l-l-o
PHP
18