0% found this document useful (0 votes)
22 views

PHP Mod5

Uploaded by

garyvee366
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

PHP Mod5

Uploaded by

garyvee366
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 163

array() Creates an array

Changes all keys in an array to lowercase or


array_change_key_case()
uppercase
array_chunk() Splits an array into chunks of arrays
Returns the values from a single column in the
array_column()
input array
Creates an array by using the elements from one
array_combine()
"keys" array and one "values" array
array_count_values() Counts all the values of an array
Compare arrays, and returns the differences
array_diff()
(compare values only)
Compare arrays, and returns the differences
array_diff_assoc()
(compare keys and values)
Compare arrays, and returns the differences
array_diff_key()
(compare keys only)
Compare arrays, and returns the differences
array_diff_uassoc() (compare keys and values, using a user-defined
key comparison function)
Compare arrays, and returns the differences
array_diff_ukey() (compare keys only, using a user-defined key
comparison function)
array_fill() Fills an array with values
array_fill_keys() Fills an array with values, specifying keys
Filters the values of an array using a callback
array_filter()
function
Flips/Exchanges all keys with their associated
array_flip()
values in an array
Compare arrays, and returns the matches
array_intersect()
(compare values only)
Compare arrays and returns the matches
array_intersect_assoc()
(compare keys and values)
Compare arrays, and returns the matches
array_intersect_key()
(compare keys only)
Compare arrays, and returns the matches
array_intersect_uassoc() (compare keys and values, using a user-defined
key comparison function)
Compare arrays, and returns the matches
array_intersect_ukey() (compare keys only, using a user-defined key
comparison function)
array_key_exists() Checks if the specified key exists in the array
array_keys() Returns all the keys of an array
Sends each value of an array to a user-made
array_map()
function, which returns new values
array_merge() Merges one or more arrays into one array
Merges one or more arrays into one array
array_merge_recursive()
recursively
array_multisort() Sorts multiple or multi-dimensional arrays
Inserts a specified number of items, with a
array_pad()
specified value, to an array
array_pop() Deletes the last element of an array
array_product() Calculates the product of the values in an array
Inserts one or more elements to the end of an
array_push()
array
array_rand() Returns one or more random keys from an array
Returns an array as a string, using a user-defined
array_reduce()
function
Replaces the values of the first array with the
array_replace()
values from following arrays
Replaces the values of the first array with the
array_replace_recursive()
values from following arrays recursively
array_reverse() Returns an array in the reverse order
Searches an array for a given value and returns
array_search()
the key
Removes the first element from an array, and
array_shift()
returns the value of the removed element
array_slice() Returns selected parts of an array
Removes and replaces specified elements of an
array_splice()
array
array_sum() Returns the sum of the values in an array
Compare arrays, and returns the differences
array_udiff() (compare values only, using a user-defined key
comparison function)
Compare arrays, and returns the differences
(compare keys and values, using a built-in
array_udiff_assoc()
function to compare the keys and a user-defined
function to compare the values)
Compare arrays, and returns the differences
array_udiff_uassoc() (compare keys and values, using two user-defined
key comparison functions)
Compare arrays, and returns the matches
array_uintersect() (compare values only, using a user-defined key
comparison function)
Compare arrays, and returns the matches
(compare keys and values, using a built-in
array_uintersect_assoc()
function to compare the keys and a user-defined
function to compare the values)
Compare arrays, and returns the matches
array_uintersect_uassoc() (compare keys and values, using two user-defined
key comparison functions)
array_unique() Removes duplicate values from an array
Adds one or more elements to the beginning of an
array_unshift()
array
array_values() Returns all the values of an array
Applies a user function to every member of an
array_walk()
array
Applies a user function recursively to every
array_walk_recursive()
member of an array
Sorts an associative array in descending order,
arsort()
according to the value
Sorts an associative array in ascending order,
asort()
according to the value
compact() Create array containing variables and their values
count() Returns the number of elements in an array
current() Returns the current element in an array
Deprecated from PHP 7.2. Returns the current key
each()
and value pair from an array
Sets the internal pointer of an array to its last
end()
element
Imports variables into the current symbol table
extract()
from an array
in_array() Checks if a specified value exists in an array
key() Fetches a key from an array
Sorts an associative array in descending order,
krsort()
according to the key
Sorts an associative array in ascending order,
ksort()
according to the key
list() Assigns variables as if they were an array
Sorts an array using a case insensitive "natural
natcasesort()
order" algorithm
natsort() Sorts an array using a "natural order" algorithm
next() Advance the internal array pointer of an array
pos() Alias of current()
prev() Rewinds the internal array pointer
range() Creates an array containing a range of elements
Sets the internal pointer of an array to its first
reset()
element
rsort() Sorts an indexed array in descending order
shuffle() Shuffles an array
sizeof() Alias of count()
sort() Sorts an indexed array in ascending order
Sorts an array by values using a user-defined
uasort()
comparison function
Sorts an array by keys using a user-defined
uksort()
comparison function
Sorts an array using a user-defined comparison
usort()
function

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

PHP Predefined Date/Time Constants

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 )

[1] => Array (


– [0] => c
– [1] => d )
– [2] => e ) )
array_change_key_case()
• The array_change_key_case() function changes
all keys in an array to lowercase or uppercase.
• Syntax
• array_change_key_case(array,case);
Parameter
• array Required. Specifies the array to use
• case Optional. Possible values:
CASE_LOWER - Default value. Changes the keys
to lowercase
CASE_UPPER - Changes the keys to uppercase
• <?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=
>"43");
print_r(array_change_key_case($age,CASE_LO
WER));
?>
Output
Array ( [peter] => 35 [ben] => 37 [joe] => 43
Array_Combine
• The array_combine() function creates an array
by using the elements from one "keys" array
and one "values" array.
• Note: Both arrays must have equal number of
elements!
Syntax
array_combine(keys,values);
keys Required. Array of keys
values Required. Array of values
• <?php
$fname=array("Peter","Ben","Joe");
$age=array("35","37","43");
$c=array_combine($fname,$age);
print_r($c);
?>
Output
Array ( [Peter] => 35 [Ben] => 37 [Joe] => 43 )
array_count_values()
• The array_count_values() function counts all
the values of an array.
Syntax
• array_count_values(array)
• array Required. Specifying the array to count
values of
array_diff_assoc
• Computes the difference of arrays with
additional index check
Syntax
• array array_diff_assoc ( array $array1 , array
$array2 [, array $... ] )
Example
Returns an array containing all the values from
array1 that are not present in any of the other
arrays.
• <?php
$array1 = array("a" => "green", "b" => "brown", "
c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result = array_diff_assoc($array1, $array2);
print_r($result);
?>
• Array (
• [b] => brown
• [c] => blue
• [0] => red )
array_diff_key
• — Computes the difference of arrays using keys for
comparison
Description
• array array_diff_key ( array $array1 , array $array2 [,
array $... ] )
• Compares the keys from array1 against the keys from
array2 and returns the difference. This function is like
array_diff() except the comparison is done on the keys
instead of the values.
Return values
Returns an array containing all the entries from array1
whose keys are not present in any of the other arrays.
• <?php
$array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'pu
rple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'c
yan' => 8);
var_dump(array_diff_key($array1, $array2));
?>
output:
array(2) {
["red"]=> int(2)
["purple"]=> int(4)
}
array_diff

• Computes the difference of arrays


Description
• array array_diff ( array $array1 , array $array2 [,
array $... ] )
• Compares array1 against array2 and returns the
difference.
Return value
Returns an array containing all the entries from
array1 that are not present in any of the other
arrays.
• <?php
$array1 = array("a" => "green", "red", "blue", "red
");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

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');

$key = array_search('green', $array); // $key =


2;
$key = array_search('red', $array); // $key = 1
;
?>
array_shift
• — Shift an element off the beginning of array
Description
• mixed array_shift ( array &$array )
• array_shift() shifts the first value of the array
off and returns it, shortening the array by one
element and moving everything down.
• All numerical array keys will be modified to
start counting from zero while literal keys
won't be touched.
• <?php
$stack = array("orange", "banana", "apple", "raspberry
");
$fruit = array_shift($stack);
print_r($stack);
?>
• The above example will output:
Array (
[0] => banana
[1] => apple
[2] => raspberry )
array_slice
• — Extract a slice of the array
Description
• array array_slice ( array $array , int $offset [,
int $length = NULL [, bool $preserve_keys =
false ]] )
• array_slice() returns the sequence of
elements from the array array as specified by
the offset and length parameters.
• <?php
$input = array("a", "b", "c", "d", "e");
$output = array_slice($input, 2); // returns "c", "d", and "e"
$output = array_slice($input, -2, 1); // returns "d"
$output = array_slice($input, 0, 3); // returns "a", "b", and "c"
// note the differences in the array keys
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));
?>
Output:
Array (
[0] => c
[1] => d )
Array (
[2] => c
[3] => d )
array_splice
• — Remove a portion of the array and replace
it with something else
Description
• array array_splice ( array &$input , int $offset
[, int $length = 0 [, mixed $replacement ]] )
• Removes the elements designated by offset
and length from the input array, and replaces
them with the elements of the replacement
array, if supplied.
• <?php
$input = array("red", "green", "blue", "yellow");
$a=array_splice($input, 2);
// $input is now array("red", "green")
$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, -1);
// $input is now array("red", "yellow")
$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, count($input), "orange");
// $input is now array("red", "orange")
array_unshift
• — Prepend one or more elements to the
beginning of an array
Description
• int array_unshift ( array &$array , mixed $var [,
mixed $... ] )
• array_unshift() prepends passed elements to the
front of the array. Note that the list of elements
is prepended as a whole, so that the prepended
elements stay in the same order. All numerical
array keys will be modified to start counting from
zero while literal keys won't be touched.
• <?php
$queue = array("orange", "banana");
array_unshift($queue, "apple", "raspberry");
print_r($queue);
?>
• The above example will output:
• Array ( [0] => apple [1] => raspberry [2] =>
orange [3] => banana )
array_values
• — Return all the values of an array
Description
• array array_values ( array $input )
• array_values() returns all the values from the
input array and indexes numerically the array.
• <?php
$array = array("size" => "XL", "color" => "gold"
);
print_r(array_values($array));
?>
• The above example will output:
• Array ( [0] => XL [1] => gold )
arsort
• — Sort an array in reverse order and maintain
index association
Description
• bool arsort ( array &$array [, int $sort_flags =
SORT_REGULAR ] )
• This function sorts an array such that array
indices maintain their correlation with the
array elements they are associated with.
• <?php
$fruits = array("d" => "lemon", "a" => "orange", "
b" => "banana", "c" => "apple");
arsort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>
• The above example will output:
• a = orange d = lemon b = banana c = apple
asort
• — Sort an array and maintain index association
Description
• bool asort ( array &$array [, int $sort_flags =
SORT_REGULAR ] )
• This function sorts an array such that array
indices maintain their correlation with the array
elements they are associated with. This is used
mainly when sorting associative arrays where the
actual element order is significant.
• <?php
$fruits = array("d" => "lemon", "a" => "orange", "
b" => "banana", "c" => "apple");
asort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>
• The above example will output:
• c = apple b = banana d = lemon a = orange
count
• — Count all elements in an array, or
something in an object
Description
• int count ( mixed $var [, int $mode =
COUNT_NORMAL ] )
• Counts all elements in an array, or something
in an object.
• <?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
$result = count($a);
// $result == 3
$b[0] = 7;
$b[5] = 9;
$b[10] = 11;
$result = count($b);
// $result == 3
$result = count(null);
// $result == 0
$result = count(false);
// $result == 1
?>
list
• — Assign variables as if they were an array
Description
• array list ( mixed $varname [, mixed $... ] )
• Like array(), this is not really a function, but a
language construct. list() is used to assign a
list of variables in one operation.
• <?php
$info = array('coffee', 'brown', 'caffeine');
// Listing all the variables
list($drink, $color, $power) = $info;
echo "$drink is $color and $power makes it special.\n";
// Listing some of them
list($drink, , $power) = $info;
echo "$drink has $power.\n";
// Or let's skip to only the third one
list( , , $power) = $info;
echo "I need $power!\n";
// list() doesn't work with strings
list($bar) = "abcde";
var_dump($bar); // NULL
sort
• — Sort an array
Description
• bool sort ( array &$array [, int $sort_flags =
SORT_REGULAR ] )
• This function sorts an array. Elements will be
arranged from lowest to highest when this
function has completed.
• <?php
$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
echo "fruits[" . $key . "] = " . $val . "\n";
}
?>
• The above example will output:
• fruits[0] = apple fruits[1] = banana fruits[2] = lemon
fruits[3] = orange
range
• — Create an array containing a range of
elements
• Description
• array range ( mixed $start , mixed $limit [,
number $step = 1 ] )
• Create an array containing a range of
elements.
• <?php
// array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
foreach (range(0, 12) as $number) {
echo $number;
}
// The step parameter was introduced in 5.0.0
// array(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
foreach (range(0, 100, 10) as $number) {
echo $number;
}
// Use of character sequences introduced in 4.1.0
// array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i');
foreach (range('a', 'i') as $letter) {
echo $letter;
}
// array('c', 'b', 'a');
foreach (range('c', 'a') as $letter) {
echo $letter;
}
?>
shuffle
• — Shuffle an array
• Description
• bool shuffle ( array &$array )
• This function shuffles (randomizes the order
of the elements in) an array.
• <?php
$numbers = range(1, 20);
shuffle($numbers);
foreach ($numbers as $number) {
echo "$number ";
}
?>
• sizeof — Alias of count()
Description
• This function is an alias of: count().
• The in_array() function searches an array for a specific value.
• Note: If the search parameter is a string and the type parameter is
set to TRUE, the search is case-sensitive.
• Syntax
• in_array(search,array,type)

Parameter Description
• search -Specifies the what to search for
• array. Specifies the array to search
• type Optional. If this parameter is set to TRUE, the in_array()
function searches for the search-string and specific type in the
array.
• <?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");
if (in_array("Glenn", $people))
{
echo "Match found";
}
else
{
echo "Match not found";
}
?>
PHP Function
A function is a block of code to accomplish a specific task. A function is
executed when it is called. A function returns or does not return a value;

A function that does not return a value


The following syntax can be used to define a function that deos not return a
value.

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>

A function that returns a value


When you want to get the value generated from a function to be used
elsewhere in your code, you will need to defind a function that can return a
value. The return keyword is used to return the value of the function to
another function or code block that calls it.

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.

 The GET Method


 The POST Method
Before the browser sends the information, it encodes it using a scheme called URL
encoding. In this scheme, name/value pairs are joined with equal signs and different
pairs are separated by the ampersand.
name1=value1&name2=value2&name3=value3
Spaces are removed and replaced with the + character and any other
nonalphanumeric characters are replaced with a hexadecimal values. After the
information is encoded it is sent to the server.

The GET Method


The GET method sends the encoded user information appended to the page request.
The page and the encoded information are separated by the ? character.
http://www.test.com/index.htm?name1=value1&name2=value2
 The GET method produces a long string that appears in your server logs, in the browser's
Location: box.
 The GET method is restricted to send upto 1024 characters only.
 Never use GET method if you have password or other sensitive information to be sent to
the server.
 GET can't be used to send binary data, like images or word documents, to the server.
 The data sent by GET method can be accessed using QUERY_STRING environment
variable.
 The PHP provides $_GET associative array to access all the sent information using GET
method.
Try out following example by putting the source code in test.php script.
<?php
if( $_GET["name"] || $_GET["age"] ) {
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";

exit();
}
?>
<html>
<body>

<form action = "<?php $_PHP_SELF ?>" method = "GET">


Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>

</body>
</html>
It will produce the following result −

The POST Method


The POST method transfers information via HTTP headers. The information is
encoded as described in case of GET method and put into a header called
QUERY_STRING.
 The POST method does not have any restriction on data size to be sent.
 The POST method can be used to send ASCII as well as binary data.
 The data sent by POST method goes through HTTP header so security depends on HTTP
protocol. By using Secure HTTP you can make sure that your information is secure.
 The PHP provides $_POST associative array to access all the sent information using
POST method.
Try out following example by putting the source code in test.php script.
<?php
if( $_POST["name"] || $_POST["age"] ) {
if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {
die ("invalid name and name should be alpha");
}
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";

exit();
}
?>
<html>
<body>

<form action = "<?php $_PHP_SELF ?>" method = "POST">


Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>

</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>

<form action = "<?php $_PHP_SELF ?>" method = "POST">


Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>

</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

// define variables and set to empty values


$name = $email = $gender = $comment = $website = "";

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>

<form method = "post" action = "/view.php">


<table>
<tr>
<td>Name:</td>
<td><input type = "text" name = "name"></td>
</tr>

<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.

• Some commonly used string functions include:


• - strlen()
• - str_replace()
• - strpos()
• - substr()
• - strtoupper() and strtolower()
strlen() - Get the Length of a
String
• The strlen() function returns the length of a string
(number of characters).

• 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

10/10/2024 Prof R Lokeshkumar


URLs and web servers

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)

Web/Application Server Database

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:

• The above URL tells the server facebook.com to run the


program home.php and send back its output

4
Server-Side web programming
• Server-side pages are programs written using one of
many web programming languages/frameworks

• Examples: PHP, Java/JSP, Ruby on Rails, ASP.NET, Python,


Perl etc

5
Server-Side web programming
(cont.)

• Also called server side scripting:

• Dynamically edit, change or add any content to a Web page


• Respond to user queries or data submitted from HTML forms
• Access any data or databases and return the results to a
browser
• Customize a Web page to make it more useful for individual
users
• Provide security since your server code cannot be viewed
from a browser

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

• Each language/framework has its pros and cons


• we use PHP

7
What is PHP?

•PHP stands for "PHP Hypertext Preprocessor"


•Server-side scripting language
•Used to make web pages dynamic:
• provide different content depending on context
• interface with other services: database, e-mail,
etc.
• authenticate users
• process form information
•PHP code can be embedded in HTML code
8
Lifecycle of a PHP web request

Hello.php
Hello world!

User’s computer Server computer 9


Why PHP?

•Free and open source


•Compatible
• As of November 2023, there were more than 120
million websites (domain names) using PHP.

•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

• Contents of a .php file between <?php and ?> are executed


as PHP code
• All other contents are output as pure HTML
• We can switch back and forth between HTML and PHP
"modes" 14
Console output: print
print "text";
PHP

print "Hello, World!\n";


print "Escape \"chars\" are the SAME as in Java!\n";
print "You can have
line breaks in a string.";
print 'A string can use "single-quotes". It\'s cool!';
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

 names are case sensitive


 names always begin with $, on both declaration
and usage
 always implicitly declared by assignment (type is
not written)
 a loosely typed language (like JavaScript or Python)
16
Variables
 basic types: int, float, boolean, string, array, object,
NULL
 test
type of variable with is_type functions, e.g.
is_string
 gettype function returns a variable's type as a string

 PHP converts between types automatically in many


cases:
 string→ int auto-conversion on +
 int → float auto-conversion on /

 type-cast with (type):


 $age = (int) "21"; 17
Arithmetic operators
 + - * / % . ++ --
 = += -= *= /= %= .=
 many operators auto-convert types: 5 + "7" is 12

18
Comments
# single-line comment
// single-line comment
/*
multi-line comment
*/ PHP

 like Java, but # is also allowed


a lot of PHP code uses # comments instead of //

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

• zero-based indexing using bracket notation


• there is no char type; each letter is itself a String
• string concatenation operator is . (period), not +
• 5 + "2 turtle doves" === 7
• 5 . "2 turtle doves" === "52 turtle
doves"
• can be specified with "" or ''
30
String Functions
# index 0123456789012345
$name = "Stefanie Hatcher";
$length = strlen($name);
$cmp = strcmp($name, "Brian Le");
$index = strpos($name, "e");
$first = substr($name, 9, 5);
$name = strtoupper($name);
PHP

31
String Functions (cont.)

Name Java Equivalent


strlen length
strpos indexOf
substr substring
strtolower, strtoupper toLowerCase, toUpperCase
trim trim
explode, implode split, join
strcmp compareTo

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

 strings inside " " are interpreted


 variables that appear inside them will have their
values inserted into the string
 strings inside ' ' are not interpreted:
print ' You are $age years old.\n '; # You are $age years
old. \n PHP

33
Interpreted Strings (cont.)
print "Today is your $ageth birthday.\n"; # $ageth not
found
print "Today is your {$age}th birthday.\n";
PHP

 if necessary to avoid ambiguity, can enclose


variable in {}

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

 it has been deleted using the unset function

 can test if a variable is NULL using the isset


function
 NULL prints as an empty string (no output) 35
for loop (same as Java)
for (initialization; condition; update) {
statements;
}
PHP

for ($i = 0; $i < 10; $i++) {


print "$i squared is " . $i * $i . ".\n";
}
PHP

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)

 arrays with 0 elements

 FALSE prints as an empty string (no output); TRUE


prints as a 1
37
if/else statement
if (condition) {
statements;
} elseif (condition) {
statements;
} else {
statements;
}
PHP

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

abs ceil cos floor log log10 max


min pow rand round sin sqrt tan
math constants
M_PI M_E M_LN2

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

• int for integers and float for reals


• division between two int values can produce a float

41
Module : 5
PHP Arrays - Functions

10/10/2024 Prof R Lokeshkumar


Basic PHP Syntax
Arrays
Strings and regular expressions

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

$a = array(); # empty array (length 0)


$a[0] = 23; # stores 23 at index 0 (length 1)
$a2 = array("some", "strings", "in", "an", "array");
$a2[] = "Ooh!"; # add string to end (at index 5)
PHP

• Append: use bracket notation without specifying an index


• Element type is not specified; can mix types

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

• the array in PHP replaces many other collections in Java


• list, stack, queue, set, map, ...

5
foreach loop
foreach ($array as $variableName) {
...
} PHP

$fellowship = array(“Frodo", “Sam", “Gandalf",


“Strider", “Gimli", “Legolas", “Boromir");
print “The fellowship of the ring members are: \n";
for ($i = 0; $i < count($fellowship); $i++) {
print "{$fellowship[$i]}\n";
}
print “The fellowship of the ring members are: \n";

foreach ($fellowship as $fellow) {


print "$fellow\n";
} 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

$test = “Hello World! \n”;


print strpos($test, “o”);
print strpos($test, “o”, 5); 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

<h2> The answer is <?= 6 * 7 ?> </h2>


PHP

The answer is 42
output

• PHP expression block: a small piece of PHP that evaluates and


embeds an expression's value into HTML
• <?= expression ?> is equivalent to:

<?php print expression; ?>


PHP

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

This is a level 1 heading.


This is a level 2 heading.
This is a level 3 heading. output

16
Functions
function name(parameterName, ..., parameterName) {
statements;
} PHP

function quadratic($a, $b, $c) {


return -$b + sqrt($b * $b - 4 * $a * $c) / (2
* $a);
} PHP

• parameter types and return types are not written


• a function with no return statements implicitly returns NULL

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

• if no value is passed, the default will be used

18

You might also like