Sie sind auf Seite 1von 636

INTELLIBITZ

Technologies
PHP Web Programming
TD_PHP_V1.0.0

IntelliBitz Technologies
Training Division
168, Medavakkam Main Road
Madipakkam, Chennai 91.
PH: +91 044 2247 5106
www.intellibitz.com
training@intellibitz.com
www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

PHP WEB
PROGRAMMING.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

CHAPTER 1

STARTING WITH PHP.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

PHP First Steps - Overview


● PHP and the WWW
● PHP as a server-side language
● What's so great about PHP?
● PHP in action
● PHP basics

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

PHP and the Web


● www.intellibitz.com Is typed in firefox
● Firefox sends a message over the internet to
the computer named www.intellibitz.com
● Apache, a program running on
www.intellibitz.com, gets the message and
asks the PHP interpreter, another program
running on the www.intellibitz.com computer,
“what does /index.php look like?”

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

PHP and the Web


● The PHP interpreter reads the file
/var/www/html/index.php from disk drive
● The PHP interpreter runs the commands in
index.php, possibly exchanging data with a
database program such as MySQL
● The PHP interpreter takes the index.php
program output and sends it back to Apache
as answer

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

PHP and the Web


● Apache sends the page contents it got from
the PHP interpreter back to your computer
over the Internet in response to Firefox
● Firefox displays the page on the screen,
following the instructions of the HTML tags in
the page

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

PHP – a server-side language


● PHP runs on the web server
● Javascript and Flash in contrast, are client-
side because they run on a web client
● The instructions in a PHP program cause the
PHP interpreter on a web server to output a
web page. The instructions in Javascript
cause Firefox to run browser commands.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

What's So Great About PHP?


● PHP is free
● PHP is cross-platform
● PHP is widely used
● PHP hides its complexity
● PHP is built for Web Programming

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

PHP in action
● The PHP interpreter runs the commands
between <?php ?> tags
● PHP processing form data via $_POST
● String syntax called a 'here document'
● Using PHP internal library functions like
number_format ()
● Displaying infromation from a database

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Basic Rules of PHP Programs


● Start and End Tags
● Whitespace and Case-Sensitivity
● Comments

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● PHP's usage by a web server to create a
response to send back to browser
● PHP as a server-side language, contrasting
with a Javascript a client-side language
● PHP is free, cross-platform, widely-used
● PHP basics, program structure, process
form, and talk to databases

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

CHAPTER 2

TEXT AND NUMBERS

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Working with Text and Numbers


● Defining Text Strings
● Validating and formatting text
● Manipulating Text
● Numbers
● Arithmetic Operators
● Variables
● Putting variables inside strings

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Text
● Pieces of text are called strings
● String can even contain binary file such as
image or sound
● String is surrounded by a single quotes..
single quotes are delimiters
● Backslash \ to be used for escaping
● The escape character can itself be escaped

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Defining Text Strings


● Variable names in a double-quoted string will
be substituted with its value.This is called as
variable interpolation.
● Here documents obey the same escape-
character and variable substitution rules
● Use a . (period) to combine two strings.The
. is the cancatenation.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Manipulating Text
● Validating string using trim () and strlen ()
● To compare two strings, use the equality
operator (==)
● Use strcasecmp () to compare strings
ignoring case

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Formatting Text
● Use printf () with a format string and the
items to print
● Zero-padding, displaying signs with printf ()
● Use of strtolower (), strtoupper (), ucwords
(),ucfirst() substr (), str_replace ()

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

String Functions.
● $length = strlen($string);
● $arrayStr = explode($separator,$string);
● $str = implode($separator,$arrayStr);
● $trimStr = trim($string);
● $resultStr = str_replace($old,$new,$full);
● Join() alias of implode().

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

String Functions
● $padded = str_pad ($string,$length)
● The returned string is atleast $length characters long.
● $repeat = str_repeat($string,$n)
● $string is repeated $n times and returned as string.
● $array= str_split($string);
● This function returns an array comprising the
characters that make up the string.
● str_word_count
● Return information about words used in a string

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

String functions
● $substring = substr($string,$n,$length)
● The portion of the string starting from the $n th
character for $length number of character is returned.
● If $n is negative the substring wil start that many
characters from end of the string.
● If $length is negative ,that many characters will be
omitted from end of the string.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

String functions
● substr_compare
● int substr_compare ( string $main_str, string $str, int
$offset [, int $length [, bool $case_insensitivity]] )
– substr_compare() compares main_str from position offset
with str up to length characters.
– Returns < 0 if main_str from position offset is less than str, >
0 if it is greater than str, and 0 if they are equal. If length is
equal or greater than length of main_str and length is set,
substr_compare() prints warning and returns FALSE.
● If case_insensitivity is TRUE, comparison is case
insensitive.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

String functions
● substr_replace
● mixed substr_replace ( mixed $string, string
$replacement, int $start [, int $length] )
– Replace text within a portion of a string
● substr_count
● int substr_count ( string $haystack, string $needle [, int
$offset [, int $length]] )
– substr_count() returns the number of times the needle
substring occurs in the haystack string. Please note that
needle is case sensitive.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

String functions.
● strtolower(),strtoupper()
● Converts the case to lower and upper respectively.
● strcmp($string1,$string2)
● Returns 0 if both are equal
● Returns positive int if first string has higher ASCII
value.
● Returns negative int if second string has higher ASCII
value.
● similar_text (string $first,string $second
● Calculate the similarity between two strings
– It returns the number matching characters in both string

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

String functions
● printf($format,$var1.$var2...);
● The $format argument returns how the subsequent
arguments are printed.
● $array = sscanf($string,$format);
● The returned array contains each extracted value from
the string according to the specified format.
● $found = strpbrk($string,$characters)
● The string is scanned for any of the characters.if match
is found it returns a string starting from the character it
just matched to end of the string.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

String functions.
● $res= strpos($bigstring,$search)
● The function returns the position of the $search string
in $bigstring
● rtrim(),ltrim(),str_ireplace(),strcasecmp(),
strnatcmp(),strnatcasecmp(),stripos(),
strrpos().Chop is alias of rtrim
● string chr ( int $ascii )
● Returns a one-character string containing the character
specified by ascii

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

String functions
● strrev
● Reverse a string
● chunk_split — Split a string into smaller
chunks
● string chunk_split ( string $body [, int $chunklen [,
string $end]] )
● string convert_cyr_string ( string $str, string
$from, string $to )

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

String functions
● strstr
● Find first occurrence of a string
– string strstr ( string $haystack, string $needle )
● Returns part of haystack string from the first
occurrence of needle to the end of haystack.
● If needle is not found, returns FALSE.
● If needle is not a string, it is converted to an integer
and applied as the ordinal value of a character.
● Stristr() - case insensitive
● Strchr
● Alias of strstr()

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

String functions
● Strtok()
● string strtok ( string $str, string $token )
– strtok() splits a string (str) into smaller strings (tokens), with
each token being delimited by any character from token.
● Strtr()
● string strtr ( string $str, string $from, string $to )
– This function returns a copy of str, translating all occurrences
of each character in from to the corresponding character in
to.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

String functions
● strcspn
● int strcspn ( string $str1, string $str2 [, int $start [, int
$length]] )
● Find length of initial segment not matching mask
● Returns the length of the initial segment of str1 which
does not contain any of the characters in str2.
● Strcoll
● Locale based string comparison
● If the current locale is C or POSIX, this function is
equivalent to strcmp().
● Note that this comparison is case sensitive, and unlike
strcmp() this function is not binary safe.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

String functions
● convert_uuencode(),convert_uudecode().
● Levenshtein ()
– Calculate Levenshtein distance between two
strings or -1, if one of the argument strings is
longer than the limit of 255 characters.
● str_rot13
● Perform the rot13 transform on a string
● The ROT13 encoding simply shifts every letter by 13
places in the alphabet while leaving non-alpha
characters untouched.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

String functions
● string addslashes ( string $str )
● Returns a string with backslashes before characters
that need to be quoted in database queries etc. These
characters are single quote ('), double quote ("),
backslash (\) and NUL (the NULL byte).
● addcslashes(),stripcslashes(), stripslashes().
● str_shuffle
● Randomly shuffles a string
● str_split
● Convert a string to an array

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

String functions
● string htmlentities ( string $string [, int
$quote_style [, string $charset]] )
● Convert all applicable characters to HTML entities
● ENT_COMPAT Will convert double-quotes and leave
single-quotes alone.
● ENT_QUOTES Will convert both double and single
quotes.
● ENT_NOQUOTES Will leave both double and single
quotes unconverted.
● charset-ISO-8859-1,ISO-8859-15,UTF-8.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

String functions
● Htmlspecialchars()
● Convert special characters to HTML entities.
● This function returns a string with some of these
conversions made
● '&' (ampersand) becomes '&amp;'
● '"' (double quote) becomes '&quot;' when
ENT_NOQUOTES is not set.
● ''' (single quote) becomes '&#039;' only when
ENT_QUOTES is set.
● '<' (less than) becomes '&lt;'
● '>' (greater than) becomes '&gt;'

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

String functions
● htmlspecialchars_decode
– Convert special HTML entities back to characters
– string htmlspecialchars_decode ( string $string [, int
$quote_style] )
– This function is the opposite of htmlspecialchars(). It
converts special HTML entities back to characters.Returns
the decoded string.
● nl2br
– Inserts HTML line breaks before all newlines in a string
– Returns string with '<br />' inserted before all newlines.
● strip_tags
– Strip HTML and PHP tags from a string

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

String functions
● md5($string)
● Calculates the md5 hash of a given string using RSA
Data Security, Inc. MD5 Message-Digest Algorithm,
and returns that hash. The hash is a 32-character
hexadecimal number.
● md5_file($filename)
● md5_file — Calculates the md5 hash of a given file.
● sha1
● Calculate the sha1 hash of a string

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

String functions
● soundex
● Calculate the soundex key of a string
– Soundex keys have the property that words pronounced
similarly produce the same soundex key, and can thus be
used to simplify searches in databases where you know the
pronunciation but not the spelling.
– This soundex function returns a string 4 characters long,
starting with a letter.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

String functions
● Metaphone
● Calculate the metaphone key of a string.
– Similar to soundex() metaphone creates the same key for
similar sounding words.
– It's more accurate than soundex() as it knows the basic rules
of English pronunciation. The metaphone generated keys
are of variable length.
● money_format
● Formats a number as a currency string
● number_format
● Format a number with grouped thousands

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

String functions
● ord
● Return ASCII value of character
● parse_str
● Parses the string into variables
● quoted_printable_decode
● Convert a quoted-printable string to an 8 bit string

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

String functions
● quotemeta
● Quote meta characters
● string quotemeta ( string $str )
● Returns a version of str with a backslash character (\)
before every character that is among these:
– .\+*?[^]($)
● Note: This function is binary-safe.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

String functions
● print
● Output a string
● int print ( string $arg )
● Outputs arg. Returns 1, always.
– print() is not actually a real function (it is a language
construct) so you are not required to use parentheses with
its argument list.
● sprintf
● Return a formatted string
● str_getcsv
● Parse a CSV string into an array.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

String functions
● wordwrap
– Wraps a string to a given number of characters using a string
break character
● string wordwrap ( string $str [, int $width [, string
$break [, bool $cut]]] )
– Returns a string with str wrapped at the column number
specified by the optional width parameter. The line is broken
using the (optional) break parameter.
– wordwrap() will automatically wrap at column 75 and break
using '\n' (newline) if width or break are not given.
– If the cut is set to 1, the string is always wrapped at the
specified width. So if you have a word that is larger than the
given width, it is broken apart

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

String functions
● vfprintf
● Write a formatted string to a stream
● vprintf
● Output a formatted string
● vsprintf
● Return a formatted string
– string vsprintf ( string $format, array $args )

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Type specifiers
● type specifier that says what type the argument data should be treated as. Possible types:
● % - a literal percent character. No argument is required.
● b - the argument is treated as an integer, and presented as a binary number.
● c - the argument is treated as an integer, and presented as the character with that ASCII
value.
● d - the argument is treated as an integer, and presented as a (signed) decimal number.
● e - the argument is treated as scientific notation (e.g. 1.2e+2).
● u - the argument is treated as an integer, and presented as an unsigned decimal number.
● f - the argument is treated as a float, and presented as a floating-point number (locale
aware).
● F - the argument is treated as a float, and presented as a floating-point number (non-locale
aware). Available since PHP 4.3.10 and PHP 5.0.3.
● o - the argument is treated as an integer, and presented as an octal number.
● s - the argument is treated as and presented as a string.
● x - the argument is treated as an integer and presented as a hexadecimal number (with
lowercase letters).
● X - the argument is treated as an integer and presented as a hexadecimal number (with
uppercase letters).

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Numbers
● Numbers – floating point and decimals
● Arithmetic operators
● +, -, *, /, %
● Operator precedence
● Grouping operations inside parentheses, will
execute whats inside the parentheses first

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Variables
● In PHP, variables are denoted by $ followed
by the variable's name
● Use = to assign value to a variable
● Variable names must begin with letter or an
underscore
● Variable names are case-sensitive
● Avoid variable names differ by letter case
● Avoid using variable names as function
names.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Operating on Variables
● Arithmetic and string operators work on
variables just as they do on literals
● Operator followed by = means “apply this
operator to the variable”
● +=, .=, ++, --
● Variable interpolation and curly braces

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Number functions
● $absvalue = abs($number)
● If $number is negative the value returned is positive.
● $remainder = $dividend % $divisor;
● % called modulus operator,returns the remainder.
● $result = pow($number,$pow);
● PHP does not have power operator. This function must
be used instead.
● $root = sqrt($number)

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Number functions
● $ceilinged = ceil($number);
● Rounds a fractional number up to next integer.
● $floored = floor($number);
● Same as ceil but returned value is still a float type
● $rounded = round($number);
● The function rounds the number to the nearest whole
number.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Number functions
● $maximum = max ($array);
● $minimum = min($array);
● $newNumber =
base_convert($number,$oldbase,$newbase)
;
● This function converts a number in any base , up to
base 36,to a number in any other base,again upto
base 36.
● $result = rand($min,$max)
● Generates random numbers between $min and $max

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Number functions
● $result = exp($power);
● The function returns the natural base 'e' raised to the
specified power.
● $result = log($number,$base);
● This function returns the logarithm of the specified
number to the base provided.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Number functions
● sin,cos,tan,sinh,cosh,tanh,asin,asinh,acos,
acosh,atan,atanh.
● Float atan2(float $y,float $x)
● This function calculates the arc tangent of the two
variables x and y. It is similar to calculating the arc
tangent of y / x, except that the signs of both
arguments are used to determine the quadrant of the
result.
● The function returns the result in radians, which is
between -PI and PI (inclusive).

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Number functions
● dechex,decoct,decbin.
● fmod,hypot.
● is_finite, is_infinite,is_nan.
● deg2rad,rad2deg,pi.
● float lcg_value ( void )
● lcg_value() returns a pseudo random number in the
range of (0, 1). Combined linear congruential
generator.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Number functions
● mt_rand()
● By default, PHP uses the libc random number
generator with the rand() function.The mt_rand() uses
a random number generator with known characteristics
using the » Mersenne Twister, which will produce
random numbers four times faster than what the
average libc rand() provides.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Defining strings in 3 different ways: single
quotes, double quotes, and a here document
● Escaping: what it is and what characters
need to be escaped in each kind of string
● Validating a string by checking its length,
removing leading and trailing whitespace
● Formatting string with printf ()

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Manipulating the case of string with
strtolower (), strtoupper () or ucwords ()
● Selecting part of a string with substr ()
● Changing part of a string with str_replace ()
● Defining numbers in your programs
● Doing math with numbers
● Storing values in variables

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Naming variables appropriately
● Using combined operators with variables
● Using increment and decrement operators
with variables
● Interpolating variables in strings

www.intellibitz.com training@intellibitz.com
CHAPTER 3

Making Decisions and Looping

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Making Decisions and Looping


● Understanding true and false
● Making Decisions
● Building Complicated Decisions
● Repeating Yourself

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Understanding true and false


● All expression in PHP program has a truth
value: true or false
● Most scalar values are true. All integers and
floating point (except 0 and 0.0) are true
● All strings are true except for two: an empty
string and the string containing only 0
● An empty array is false

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Control statements
● Any PHP script is built out of a series of statements.
● A statement can be an assignment, a function call, a
loop, a conditional statement or even a statement that
does nothing (an empty statement).
● Statements usually end with a semicolon.
● In addition, statements can be grouped into a statement-
group by encapsulating a group of statements with curly
braces {...}.
● A statement-group is a statement by itself as well.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Making Decisions
● If () construct runs a block of code if its test
expression is true
● Add an else to if() statement, to run different
statements when the test expression is false
● use elseif() with if() to test manyconditions
● For a given set of if() and elseif() statements,
at most one of the code blocks is run

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

If statement
● it allows for conditional execution of code
fragments.
● PHP features an if structure that is similar to
that of C:
● The expression is evaluated to its Boolean
if (expr)
statement
value. If expression evaluates to TRUE, PHP
will execute statement, and if it evaluates to
FALSE - it'll ignore it.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

If statements
● Often you'd want to have more than one <?php
statement to be executed conditionally. if ($a > $b)
● In such case there's no need to wrap each echo "a is bigger than b";
statement with an if clause. Instead, you
?>
can group several statements into a
statement group.
<?php
● If statements can be nested indefinitely
within other if statements, which provides if ($a > $b)
you with complete flexibility for conditional {
execution of the various parts of your
echo "a is bigger than b";
program.
$b = $a;
}
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

If else statement
● Often you'd want to execute a statement if <?php
a certain condition is met, and a different if ($a > $b) {
statement if the condition is not met. This
echo "a is bigger than b";
is what else is for.
● else extends an if statement to execute a } else {
statement in case the expression in the if echo "a is NOT bigger than b";
statement evaluates to FALSE. }
● The else statement is only executed if the
?>
if expression evaluated to FALSE, and if
there were any elseif expressions - only if
they evaluated to FALSE this else is
executed

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

else if
● elseif, as its name suggests, is a <?php
combination of if and else. if ($a > $b) {
● It extends an if statement to execute a
echo "a is bigger than b";
different statement in case the original if
expression evaluates to FALSE. } elseif ($a == $b) {
● However, unlike else, it will execute that echo "a is equal to b";
alternative expression only if the elseif
} else {
conditional expression evaluates to TRUE.
echo "a is smaller than b";
}
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

elseif statement
● There may be several elseifs within the same if statement. The first
elseif expression (if any) that evaluates to TRUE would be executed.
● In PHP, you can also write 'else if' (in two words) and the behavior would
be identical to the one of 'elseif' (in a single word). The syntactic
meaning is slightly different (if you're familiar with C, this is the same
behavior) but the bottom line is that both would result in exactly the
same behavior.
● The elseif statement is only executed if the preceding if expression and
any preceding elseif expressions evaluated to FALSE, and the current
elseif expression evaluated to TRUE.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

while()
● While statements tells PHP to execute the nested
while (expr)
statement(s) repeatedly, as long as the while statement
expression evaluates to TRUE.
● The value of the expression is checked each time <?php
at the beginning of the loop, so even if this value $i = 1;
changes during the execution of the nested
statement(s), execution will not stop until the end while ($i <= 10) {
of the iteration (each time PHP runs the echo $i++;
statements in the loop is one iteration). }
● Sometimes, if the while expression evaluates to
FALSE from the very beginning, the nested /* the printed value would be $i
before the increment (post-
statement(s) won't even be run once. increment) */
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

do while
● do-while loops are very similar to while loops, <?php
except the truth expression is checked at the end of $i = 0;
each iteration instead of in the beginning.
do {
● The main difference from regular while loops is that
the first iteration of a do-while loop is guaranteed to echo $i;
run as the truth expression is only checked at the } while ($i > 0);
end of the iteration).
?>
● whereas it's may not necessarily run with a regular
while loop the truth expression is checked at the
beginning of each iteration, if it evaluates to FALSE
right from the beginning, the loop execution would
end immediately.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

for statement
● A variable can be initialised once for (initialise;
unconditionally at the beginning of the loop. test condition;
● In the beginning of each iteration, test condition increment value)
statement
is checked. If it evaluates to TRUE, the loop
continues and the nested statement(s) are for ($i = 1; $i <= 10; $i++) {
executed. If it evaluates to FALSE, the echo $i;
execution of the loop ends.
}
● At the end of each iteration, increment value is
evaluated (executed). for ($i = 1; ; $i++) {
if ($i > 10) {
break;
}
echo $i;
}

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

for loop
● Each of the expressions can be empty or
$i = 1;
contain multiple expressions separated by
commas. for (; ; ) {
● Comma separated expressions in test if ($i > 10) {
condition are treated similarly to being break;
separated by the || operator but has a lower
precedence than ||. expr2 being empty means }
the loop should be run indefinitely (PHP echo $i;
implicitly considers it as TRUE, like C). $i++;
● This may not be as useless as you might think,
since often you'd want to end the loop using a }
conditional break statement instead of using for ($i = 1, $j = 0; $i <= 10; $j
the for truth expression. += $i, print $i, $i++);

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

foreach loop
● PHP 4 introduced a foreach construct, much like Perl
● This simply gives an easy way to iterate over arrays.
● foreach works only on arrays, and will issue an error when you try to use it
on a variable with a different data type or an uninitialized variable.
● There are two syntaxes; the second is a minor but useful extension of the
first:

foreach (array_expression as $value)


statement
foreach (array_expression as $key => $value)
statement

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

foreach
● The first form loops over the array given by
<?php
array_expression. On each loop, the value of the
current element is assigned to $value and the $arr = array(1, 2, 3, 4);
internal array pointer is advanced by one (so on foreach ($arr as &$value) {
the next loop, you'll be looking at the next
$value = $value * 2;
element).
● The second form does the same thing, except that }
the current element's key will be assigned to the // $arr is now array(2, 4, 6, 8)
variable $key on each loop.
foreach($arr as $key =>$val){
● you can easily modify array's elements by
preceding $value with &. This will assign print”$key=$val”;
reference instead of copying the value. }
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

foreach
● When foreach first starts executing, the
internal array pointer is automatically reset to
the first element of the array. This means
that you do not need to call reset() before a
foreach loop.
● Unless the array is referenced, foreach
operates on a copy of the specified array and
not the array itself.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

break
$i = 0; while (++$i) {
● break ends execution of the current switch ($i) {
for, foreach, while, do-while or switch
structure. case 5:
● break accepts an optional numeric echo "At 5<br />\n";
argument which tells it how many break 1; /* Exit only the switch. */
nested enclosing structures are to be
broken out of. case 10:
echo "At 10; quitting<br />\n";
break 2; /* Exit the switch and the
while. */
default:
break;
}
}

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

continue
$i = 0;
● continue is used within looping while ($i++ < 5) {
structures to skip the rest of the
echo "Outer<br />\n";
current loop iteration and continue
execution at the condition evaluation while (1) {
and then the beginning of the next echo "Middle<br />\n";
iteration. while (1) {
● Note that in PHP the switch
statement is considered a looping echo "Inner<br />\n";
structure for the purposes of continue. continue 3;
● continue accepts an optional numeric }
argument which tells it how many
echo "This never gets output.<br />\n";
levels of enclosing loops it should skip
to the end of. }
echo "Neither does this.<br />\n";
}

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

switch
<?php
● The switch statement is similar to a series of
IF statements on the same expression. In switch ($i) {
many occasions, you may want to compare case 0:
the same variable (or expression) with many echo "i equals 0";
different values, and execute a different piece
break;
of code depending on which value it equals to.
This is exactly what the switch statement is case 1:
for. echo "i equals 1";
● Note that unlike some other languages, the
break;
continue statement applies to switch and acts
similar to break. If you have a switch inside a case 2:
loop and wish to continue to the next iteration echo "i equals 2";
of the outer loop, use continue 2. break;
}
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

switch
● The switch statement executes line by line ?php
(actually, statement by statement). switch ($i) {
● In the beginning, no code is executed. Only
case 0:
when a case statement is found with a value
that matches the value of the switch echo "i equals 0";
expression does PHP begin to execute the case 1:
statements.
echo "i equals 1";
● PHP continues to execute the statements until
the end of the switch block, or the first time it case 2:
sees a break statement. echo "i equals 2";
● Thus, it is important not to forget break
}
statements to avoid mistakes.
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Alternative syntax
<?php
● PHP offers an alternative <?php if ($a == 5): ?>
if ($a == 5):
syntax for some of its control A is equal to 5
structures; namely, if, while, echo "a equals 5";
<?php endif; ?>
for, foreach, and switch. In echo "...";
each case, the basic form of elseif ($a == 6):
the alternate syntax is to
change the opening brace to echo "a equals 6";
a colon (:) and the closing echo "!!!";
brace to endif;, endwhile;, else:
endfor;, endforeach;, or
endswitch;, respectively. echo "a is neither 5 nor 6";
endif;
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

return
● If called from within a function, the return()
statement immediately ends execution of the
current function, and returns its argument as
the value of the function call.
● return() will also end the execution of an
eval() statement or script file.
● Eval() evaluates the string as PHP code.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

return
● Note that since return() is a language construct and not a function,
the parentheses surrounding its arguments are not required. It is
common to leave them out, and you actually should do so as PHP
has less work to do in this case.
● You should never use parentheses around your return variable
when returning by reference, as this will not work. You can only
return variables by reference, not the result of a statement. If you
use return ($a); then you're not returning a variable, but the result
of the expression ($a) (which is, of course, the value of $a).

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

require()
<?php
● The require() statement
includes and evaluates the require 'prepend.php';
specific file.
– Require() includes and require $somefile;
evaluates a specific file.
require ('somefile.txt');

?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

include()
● The include() statement includes and evaluates the specified file.
● The difference between include() and require() The two constructs are
identical in every way except how they handle failure.
● They both produce a Warning, but require() results in a Fatal Errorand
stops execution.
● include() does not behave this way, the script will continue regardless.
● use require() if you want a missing file to halt processing of the page.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

require_once()
● This is a behavior similar to the require()
statement, with the only difference being that
if the code from a file has already been
included, it will not be included again.
● require_once() should be used in cases
where you want to be sure that it is included
exactly once to avoid problems with function
redefinitions, variable value reassignments,
etc.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

require_once()
● Be aware, that the behaviour of
require_once() and include_once() may not
be what you expect on a non case sensitive
operating system (such as Windows).

<?php
require_once("a.php"); // this will include a.php
require_once("A.php"); // this will include a.php
//again on Windows! (PHP 4 only)
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

include_once()
● This is a behavior similar to the include()
statement, with the only difference being that
if the code from a file has already been
included, it will not be included again.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

declare
● The declare construct is used to set declare (directive)
execution directives for a block of code. The statement
syntax of declare is similar to the syntax of
<?php
other flow control constructs
● A tick is an event that occurs for every N // these are the same:
low-level statements executed by the parser // you can use this:
within the declare block.
declare(ticks=1) {
● The value for N is specified using ticks=N
within the declare blocks's directive section. // entire script here
● The event(s) that occur on each tick are }
specified using the register_tick_function()
// or you can use this:
declare(ticks=1);
// entire script here
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

ticks
● The example profiles the PHP code within the 'declare'
block, recording the time at which every second low-level
statement in the block was executed.
● This information can then be used to find the slow areas
within particular segments of code.
● This process can be performed using other methods:
using ticks is more convenient and easier to implement.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

<?php
ticks// Set up a tick handler
// A function that records the time when it is called
register_tick_function("profile");
function profile($dump = FALSE) // Initialize the function before the declare block
{ profile();
static $profile; // Run a block of code, throw a tick every
// Return the times stored in profile, then erase
2nditstatement
if ($dump) { declare(ticks=2) {
$temp = $profile; for ($x = 1; $x < 50; ++$x) {
unset($profile); echo similar_text(md5($x), md5($x*$x)), "<br />;";
return $temp; }
} }
$profile[] = microtime(); // Display the data stored in the profiler
} print_r(profile(TRUE));
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Building Complicated Decisions


● Complicated expressions can be put
together with comparison and logical
operators
● Beware of assignment versus comparison
● Beware of floating-point comparison
● Strings are compared like dictionary lookup
● Beware of strings containing numbers
● Use strcmp() to compare like dictionary for
strings containing numbers

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Repeating Yourself
● When a program does something repeatedly,
its called looping
● Use while(), for(), foreach() for looping
● Multiple expression in for() is allowed but
only one test expression is possible

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Evaluating an expression's truth value: true
or false
● Making a decision with if().
● Extending if() with else
● Extending if() with elseif()
● Putting multiple statements inside an if(),
elseif(), or else code block

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Using the equality (==) and not-equals (!=)
operators in test expressions.
● Distinguishing between assignment (=) and
equality comparison (==)
● Using the less-than (<), greater-than (>),
less-than-or-equal-to (<=), and greater-than-
or-equal-to (>=) operators in test expressions

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Comparing two floating-point numbers with
abs()
● Comparing two strings with operators
● Comparing two strings with strcmp() or
strcasecmp()
● Using the negation operator (!) in test
expressions

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Using the logical operators (&& and ||) to
build more complicated test expressions
● Repeating a code block with while ()
● Repeating a code block with for ()

www.intellibitz.com training@intellibitz.com
CHAPTER 4

WORKING WITH ARRAYS

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Working with Arrays


● Creating an Array
● Creating a Numeric Array
● Looping through Arrays
● Modifying Arrays
● Sorting Arrays
● Using Multidimensional Arrays

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Array Basics and Creation


● An array is made up of elements. Each
element has a key and a value. Only one
element with a given key can exist.
● Any string or number can be the key
● An element value can be string, number, true
or false; it can also be another array

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Creating an Array
● Assign a value to a particular array key to
create an array
● Use array() language construct
● With array(), specify a comma-delimited list
of key/value pairs
● Beware of array and scalar name collision

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Creating a Numeric Array


● Use array() with only a list of values, instead
of key/value pairs
● String keyed arrays are associative arrays
● PHP automatically uses incrementing
numbers for array keys when array creation
or add elements with empty brackets syntax
● Use count() to find the size of an array

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Looping through Arrays


● Use foreach() to run a code block once for
each element in the array
● Changing the loop variables like $key and
$value inside foreach() doesn't affect array
● Inside foreach(), the elements are accessed
in the order they were added to the array
● Use for() to access elements in numerical
key order

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Looping through Arrays


● Use array_key_exists(), to check for an
element with a certain key
● Use in_array(), to check for an element with
a particular value
● in_array is case-sensitive
● Use array_search to find the element key for
a given element value

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array()
<?php
● Create an array
● array array ( [mixed $...] ) $fruits = array (
● Returns an array of the "fruits" => array("a" => "orange", "b" =>
parameters. The parameters can "banana", "c" => "apple"),
be given an index with the => "numbers" => array(1, 2, 3, 4, 5, 6),
operator.
"holes" => array("first", 5 => "second",
"third")
);
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array
Array

<?php (

$array = array(1, 1, 1, 1, 1, 8 => 1, [0] => 1


4 => 1, 19, 3 => 13); [1] => 1
print_r($array); [2] => 1
?> [3] => 13
[4] => 1
[8] => 1
[9] => 19
)

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array()
1-based index with array()
<?php <?php
$firstquarter = array(1 => 'January', 'February',
'March');
$foo = array('bar' =>
'baz'); print_r($firstquarter);
echo "Hello {$foo['bar']}!"; ?>
// Hello baz!
The above example will output:
Array
?> (
[1] => January
[2] => February
[3] => March
)

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

sort
● Sort an array <?php
● Description
● bool sort ( array &$array [, int $fruits = array("lemon", "orange",
"banana", "apple");
$sort_flags] )
● This function sorts an array. Elements sort($fruits);
will be arranged from lowest to highest foreach ($fruits as $key => $val) {
when this function has completed. echo "fruits[" . $key . "] = " . $val .
● Note: This function assigns new keys "\n";
for the elements in array. It will remove
}
any existing keys you may have
assigned, rather than just reordering the ?>
keys. The above example will output:
● Returns TRUE on success or FALSE on fruits[0] = apple
failure. fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

rsort
● Sort an array in reverse order
● bool rsort ( array &$array [, int $sort_flags] )
● This function sorts an array in reverse order (highest to lowest).
● This function assigns new keys for the elements in array. It will remove
any existing keys you may have assigned, rather than just reordering
the keys.
● Returns TRUE on success or FALSE on failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

rsort
<?php
$fruits = array("lemon", "orange", "banana", "apple");
rsort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>
The above example will output:
0 = orange
1 = lemon
2 = banana
3 = apple

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

asort
● Sort an array and maintain index association
● bool asort ( array &$array [, int $sort_flags] )

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

● Returns TRUE on success or FALSE on failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

asort
<?php
$fruits = array("d" => "lemon", "a" => "orange",
"b" => "banana", "c" => "apple");
asort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
The fruits have been sorted in
alphabetical order, and the index
?> associated with each element has
The above example will output: been maintained.
c = apple
b = banana
d = lemon
a = orange

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

arsort
● Sort an array in reverse order and maintain index association
● bool arsort ( array &$array [, int $sort_flags] )

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

● Returns TRUE on success or FALSE on failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

arsort
<?php
$fruits = array("d" => "lemon", "a" => "orange",
"b" => "banana", "c" => "apple");
arsort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>
The fruits have been sorted in reverse
The above example will output: alphabetical order, and the index
a = orange associated with each element has been
d = lemon maintained.
b = banana
c = apple

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

ksort
● Sort an array by key <?php
● bool ksort ( array &$array [, int $sort_flags] )
● Sorts an array by key, maintaining key to $fruits = array("d"=>"lemon", "a"=>"orange",
data correlations. This is useful mainly for "b"=>"banana", "c"=>"apple");
associative arrays.
● Returns TRUE on success or FALSE on ksort($fruits);
failure. foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>
The above example will output:
a = orange
b = banana
c = apple
d = lemon

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

krsort
● Sort an array by key in reverse order <?php
● bool krsort ( array &$array [, int
$sort_flags] ) $fruits = array("d"=>"lemon", "a"=>"orange",

"b"=>"banana", "c"=>"apple");
● Sorts an array by key in reverse order,
maintaining key to data correlations. This krsort($fruits);
is useful mainly for associative arrays. foreach ($fruits as $key => $val) {

● Returns TRUE on success or FALSE on echo "$key = $val\n";


failure.
● }

?>
The above example will output:
d = lemon
c = apple
b = banana
a = orange

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

natsort
● Sort an array using a "natural order" algorithm
● bool natsort ( array &$array )
● This function implements a sort algorithm that orders
alphanumeric strings in the way a human being would while
maintaining key/value associations. This is described as a
"natural ordering". An example of the difference between this
algorithm and the regular computer string sorting algorithms
(used in sort()) can be seen below:
● Returns TRUE on success or FALSE on failure.
● natcasesort -- case insensitive.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0
<?php

natsort
$array1 = $array2 = array("img12.png",
"img10.png", "img2.png", "img1.png");

The above example will output:


sort($array1);
Standard sorting
echo "Standard sorting\n"; Array
(
print_r($array1);
[0] => img1.png
[1] => img10.png
[2] => img12.png
natsort($array2); [3] => img2.png
echo "\nNatural order sorting\n"; )
Natural order sorting
print_r($array2); Array
(
?> [3] => img1.png
[2] => img2.png
[1] => img10.png
[0] => img12.png
)

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

usort
● Sort an array by values using a user-defined comparison function
● Description
● bool usort ( array &$array, callback $cmp_function )

● This function will sort an array by its values using a user-supplied


comparison function. If the array you wish to sort needs to be sorted by
some non-trivial criteria, you should use this function.

● The comparison function must return an integer less than, equal to, or
greater than zero if the first argument is considered to be respectively
less than, equal to, or greater than the second.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
<?php
TD_PHP_V1.0.0

function cmp($a, $b)


{ usort
if ($a == $b) {
return 0; $a = array(3, 2, 5, 6, 1);
}
return ($a < $b) ? -1 : 1; usort($a, "cmp");
}
foreach ($a as $key => $value) {
echo "$key: $value\n";
}
?>
The above example will output:
0: 1
1: 2
2: 3
3: 5
4: 6

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

usort
● Note: If two members compare as equal, their order in the sorted
array is undefined. Up to PHP 4.0.6 the user defined functions would
keep the original order for those elements, but with the new sort
algorithm introduced with 4.1.0 this is no longer the case as there is no
solution to do so in an efficient way.

● Note: This function assigns new keys for the elements in array. It will
remove any existing keys you may have assigned, rather than just
reordering the keys.

● Returns TRUE on success or FALSE on failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

uasort
● Sort an array with a user-defined comparison function and maintain
index association
● bool uasort ( array &$array, callback $cmp_function )
● 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. The comparison function is user-defined.
● Returns TRUE on success or FALSE on failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

uksort
● Sort an array by keys using a user-defined comparison function
● bool uksort ( array &$array, callback $cmp_function )

● uksort() will sort the keys of an array using a user-supplied comparison


function. If the array you wish to sort needs to be sorted by some non-
trivial criteria, you should use this function.

● Function cmp_function should accept two parameters which will be filled


by pairs of array keys. The comparison function must return an integer
less than, equal to, or greater than zero if the first argument is
considered to be respectively less than, equal to, or greater than the
second.

● Returns TRUE on success or FALSE on failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

<?php
function cmp($a, $b)
uksort
{
$a = ereg_replace('^(a|an|the)
$a ',='',array("John"
$a); => 1, "the Earth" => 2, "an apple" => 3,
$b = ereg_replace('^(a|an|the)
"a ',banana"
'', $b); => 4);
return strcasecmp($a, $b);
} uksort($a, "cmp");

foreach ($a as $key => $value) {


echo "$key: $value\n";
}
?>

The above example will output:


an apple: 3
a banana: 4
the Earth: 2
John: 1
www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

list
<?php
● Assign variables as if they were an
$info = array('coffee', 'brown',
array 'caffeine');
● void list ( mixed $varname, mixed $... )

// Listing all the variables
● Like array(), this is not really a function,
but a language construct. list() is used list($drink, $color, $power) = $info;
to assign a list of variables in one echo "$drink is $color and $power
operation. makes it special.\n";

● Note: list() only works on numerical // Listing some of them


arrays and assumes the numerical list($drink, , $power) = $info;
indices start at 0.
echo "$drink has $power.\n";
// Or let's skip to only the third one
list( , , $power) = $info;
echo "I need $power!\n";
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

shuffle
● Shuffle an array
● bool shuffle ( array &$array )
● This function shuffles (randomizes the order of the elements in) an
array. Note: This function assigns new keys for the elements in array. It
will remove any existing keys you may have assigned, rather than just
reordering the keys.

<?php
$numbers = range(1, 20);
shuffle($numbers);
foreach ($numbers as $number) {
echo "$number ";
}
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_change_key_case
● Returns an array with all string keys
lowercased or uppercased <?php
– array array_change_key_case ( array $input_array = array("FirSt" => 1,
$input [, int $case] ) "SecOnd" => 4);
– array_change_key_case() changes print_r(array_change_key_case($input
the keys in the input array to be all _array, CASE_UPPER));
lowercase or uppercase. ?>
– The change depends on the last
optional case parameter. The above example will output:
– You can pass two constants there, Array
CASE_UPPER and CASE_LOWER. (
[FIRST] => 1
The default is CASE_LOWER. [SECOND] => 4
– The function will leave number indices )
as is.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_chunk()
● Split an array into chunks The below example will output:
– array array_chunk ( array $input, int $size [, bool Array
$preserve_keys] ) (
– array_chunk() splits the array into several arrays [0] => Array
(
with size values in them. You may also have an [0] => a
array with less values at the end. You get the [1] => b
arrays as members of a multidimensional array )
indexed with numbers starting from zero. [1] => Array
(
[0] => c
[1] => d
)
<?php [2] => Array
(
$input_array = array('a', 'b', 'c', 'd', 'e');
[0] => e
print_r(array_chunk($input_array, 2)); )
)
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_chunk()
The below example will output:
● By setting the optional preserve_keys Array
(
parameter to TRUE, you can force [0] => Array
PHP to preserve the original keys (
from the input array. [0] => a
● If you specify FALSE new number [1] => b
indices will be used in each resulting )
[1] => Array
array with indices starting from zero. (
The default is FALSE. [2] => c
[3] => d
)
[2] => Array
(
<?php [4] => e
)
$input_array = array('a', 'b', 'c', 'd', 'e'); )
print_r(array_chunk($input_array, 2, true));
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

key
<?php
$array = array( / this cycle echoes all associative array
● Fetch a key from an 'fruit1' => 'apple', // key where value equals "apple"
associative array while ($fruit_name = current($array)) {
'fruit2' => 'orange',
● mixed key ( array
&$array ) 'fruit3' => 'grape', if ($fruit_name == 'apple') {

'fruit4' => 'apple', echo key($array).'<br />';
● key() returns the }
'fruit5' => 'apple');
index element of the
current array position. / next($array);
}
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

count
● Count elements in an array, or properties in an object
● int count ( mixed $var [, int $mode] )
● Returns the number of elements in var, which is typically an array, since
anything else will have one element.
● For objects, if you have SPL installed, you can hook into count() by
implementing interface Countable. The interface has exactly one
method, count(), which returns the return value for the count() function.
● If var is not an array or an object with implemented Countable interface,
1 will be returned. There is one exception, if var is NULL, 0 will be
returned.
● The optional mode parameter is available as of PHP 4.2.0.
● If the optional mode parameter is set to COUNT_RECURSIVE (or 1),
count() will recursively count the array. This is particularly useful for
counting all the elements of a multidimensional array. The default value
for mode is 0. count() does not detect infinite recursion.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

<?php count
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
$result = count($a); $result = count(null);
$b[0] = 7;
// $result == 3 // $result == 0
$b[5] = 9;
$b[10] = 11;
$result = count(false);
$result = count($b);
// $result == 1
// $result == 3
?>

sizeof — Alias of count()


www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

current
● Return the current element in an array
● Description
● mixed current ( array &$array )

● Every array has an internal pointer to its "current" element, which is initialized to the first
element inserted into the array.

● The current() function simply returns the value of the array element that's currently being
pointed to by the internal pointer. It does not move the pointer in any way. If the internal
pointer points beyond the end of the elements list, current() returns FALSE.
● Pos is alias of current

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

next
<?php
● Advance the internal array pointer of an
array $transport = array('foot',
● mixed next ( array &$array ) 'bike', 'car', 'plane');

● Returns the array value in the next place $mode = current($transport);


that's pointed to by the internal array // $mode = 'foot';
pointer, or FALSE if there are no more
elements. $mode = next($transport); //

$mode = 'bike';
● next() behaves like current(), with one $mode = next($transport); //
difference. It advances the internal array $mode = 'car';
pointer one place forward before returning
the element value. That means it returns $mode = prev($transport);
the next array value and advances the // $mode = 'bike';
internal array pointer by one. If advancing
the internal array pointer results in going $mode = end($transport); //
beyond the end of the element list, next() $mode = 'plane';
returns FALSE. ?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

prev
● Rewind the internal array <?php
pointer
$transport = array('foot', 'bike', 'car', 'plane');
● mixed prev ( array &$array )
● $mode = current($transport); // $mode = 'foot';
● Returns the array value in $mode
the = next($transport); // $mode = 'bike';
previous place that's pointed to
$mode = next($transport); // $mode = 'car';
by the internal array pointer, or
FALSE if there are no more $mode = prev($transport); // $mode = 'bike';
elements. $mode = end($transport); // $mode = 'plane';
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

each
● Return the current key and value pair from an array and advance the
array cursor
● Description
● array each ( array &$array )

● Returns the current key and value pair from the array array and
advances the array cursor. This pair is returned in a four-element array,
with the keys 0, 1, key, and value. Elements 0 and key contain the key
name of the array element, and 1 and value contain the data.

● If the internal pointer for the array points past the end of the array
contents, each() returns FALSE.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

each
<?php
<?php
$foo = array("bob", "fred", "jussi",
"jouni", "egon", "marliese"); $foo = array("Robert" => "Bob", "Seppo" => "Sepi");
$bar = each($foo); $bar = each($foo);
print_r($bar); print_r($bar);
?> ?>
$bar now contains the following $bar now contains the following key/value pairs:
key/value pairs:
Array
Array (
( [1] => Bob
[1] => bob [value] => Bob
[value] => bob [0] => Robert
[0] => 0 [key] => Robert
[key] => 0 )
)

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

end
● Set the internal pointer of an array to its last element
● mixed end ( array &$array )

● end() advances array's internal pointer to the last element, and returns
its value.

<?php

$fruits = array('apple', 'banana', 'cranberry');


echo end($fruits); // cranberry

?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

reset
● Set the internal pointer of an array
to its first element
● mixed reset ( array &$array )
● reset() rewinds array's internal
pointer to the first element and
returns the value of the first array
element, or FALSE if the array is
empty.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

reset
<?php
// skip two steps
next($array);
$array = array('step one', 'step two', 'step
next($array);
three', 'step four');
echo current($array) . "<br />\n"; // "step three"

// by default, the pointer is on the first element


// reset pointer, start again on step one
echo current($array) . "<br />\n"; // "step one"
reset($array);
echo current($array) . "<br />\n"; // "step one"

?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

range
● Create an array containing a range of elements
● array range ( mixed $low, mixed $high [, number $step] )
● range() returns an array of elements from low to high, inclusive. If low >
high, the sequence will be from high to low.
● New parameter: The optional step parameter was added in 5.0.0.
● If a step value is given, it will be used as the increment between elements
in the sequence. step should be given as a positive number. If not
specified, step will default to 1.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

range
?php
// array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) // array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i');

foreach (range(0, 12) as $number) { foreach (range('a', 'i') as $letter) {

echo $number; echo $letter;

} }
// array('c', 'b', 'a');

// The step parameter was introduced in 5.0.0 foreach (range('c', 'a') as $letter) {

// array(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100) echo $letter;

foreach (range(0, 100, 10) as $number) { }

echo $number; ?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

in_array()
● Checks if a value exists in an array
● bool in_array ( mixed $needle, array $haystack [, bool $strict] )

● Searches haystack for needle and returns TRUE if it is found in the


array, FALSE otherwise.
● If the third parameter strict is set to TRUE then the in_array() function
will also check the types of the needle in the haystack.
● Note: If needle is a string, the comparison is done in a case-sensitive
manner.
● Note: In PHP versions before 4.2.0 needle was not allowed to be an
array.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

in_array
<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Got Irix";
}
if (in_array("mac", $os)) {
echo "Got mac";
}
?>
The second condition fails because in_array() is case-
sensitive, so the program above will display:
Got Irix

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

extract
● Import variables into the current symbol table from an array
● nt extract ( array $var_array [, int $extract_type [, string $prefix]] )

● This function is used to import variables from an array into the current
symbol table. It takes an associative array var_array and treats keys as
variable names and values as variable values. For each key/value pair it
will create a variable in the current symbol table, subject to extract_type
and prefix parameters.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_count_values
● Counts all the values of an array <?php
– array array_count_values
$array = array(1, "hello", 1, "world", "hello");
( array $input )
● array_count_values() print_r(array_count_values($array));
returns an array using the ?>
values of the input array as
The above example will output:
keys and their frequency in
input as values. Array
(
[1] => 2
[hello] => 2
[world] => 1
)

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_sum
● Calculate the sum of values in an array
● number array_sum ( array $array )
● array_sum() returns the sum of values in an array as an integer or float.

<?php
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";
$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4);
echo "sum(b) = " . array_sum($b) . "\n";
?>
The above example will output:
sum(a) = 20
sum(b) = 6.9

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_values
● Return all the values of an array
● array array_values ( array $input ) <?php
● array_values() returns all the values $array = array("size" => "XL", "color" =>
from the input array and indexes "gold");
numerically the array. print_r(array_values($array));
?>
The above example will output:
Array
(
[0] => XL
[1] => gold
)

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_pad
● Pad array to the specified length <?php
with a value.
● array array_pad ( array $input, int $input = array(12, 10, 9);
$pad_size, mixed $pad_value )
● array_pad() returns a copy of the $result = array_pad($input, 5, 0);
input padded to size specified by
// result is array(12, 10, 9, 0, 0)
pad_size with value pad_value. If
pad_size is positive then the array
is padded on the right, if it's $result = array_pad($input, -7, -1);
negative then on the left. If the
// result is array(-1, -1, -1, -1, 12, 10, 9)
absolute value of pad_size is less
than or equal to the length of the
input then no padding takes $result = array_pad($input, 2, "noop");
place. It is possible to add most
// not padded
1048576 elements at a time.
?>

www.intellibitz.com training@intellibitz.com
www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_pop
<?php
● Pop the element off the $stack = array("orange", "banana", "apple", "raspberry");
end of array $fruit = array_pop($stack);
● mixed array_pop ( array
&$array ) print_r($stack);
● array_pop() pops and ?>
returns the last value of After this, $stack will have only 3 elements:
the array, shortening the
array by one element. If Array
array is empty (or is not (
an array), NULL will be [0] => orange
returned.
[1] => banana
[2] => apple
) and raspberry will be assigned to $fruit.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_push
<?php
● Push one or more elements $stack = array("orange", "banana");
onto the end of array array_push($stack, "apple", "raspberry");
● int array_push ( array &$array,
mixed $var [, mixed $...] ) print_r($stack);
● array_push() treats array as a ?>
stack, and pushes the passed The above example will output:
variables onto the end of array.
The length of array increases Array
by the number of variables (
pushed. [0] => orange
[1] => banana
[2] => apple
[3] => raspberry
)

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_push
● array_push has the same effect as:
● <?php
● $array[] = $var;
● ?>
● repeated for each var.
● Returns the new number of elements in the array. array_push() will raise
a warning if the first argument is not an array. This differs from the $var[]
behaviour where a new array is created.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

compact
● Create array containing variables and their values
● array compact ( mixed $varname [, mixed $...] )
● compact() takes a variable number of parameters. Each parameter can
be either a string containing the name of the variable, or an array of
variable names. The array can contain other arrays of variable names
inside it; compact() handles it recursively.
● For each of these, compact() looks for a variable with that name in the
current symbol table and adds it to the output array such that the
variable name becomes the key and the contents of the variable
become the value for that key. In short, it does the opposite of extract().
It returns the output array with all the variables added to it.
● Any strings that are not set will simply be skipped.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_product
● Calculate the product of values in an array
● number array_product ( array $array )
● array_product() returns the product of values in an array as an integer or
float.

<?php

$a = array(2, 4, 6, 8);
echo "product(a) = " . array_product($a) . "\n";

?>
The above example will output:
product(a) = 384

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_rand
● Pick one or more random entries out of an
array
● mixed array_rand ( array $input [, int $num_req]
) <?php
● array_rand() is rather useful when you want to$input = array("Neo", "Morpheus",
pick one or more random entries out of an array."Trinity", "Cypher", "Tank");
It takes an input array and an optional argument
num_req which specifies how many entries you$rand_keys = array_rand($input, 2);
want to pick - if not specified, it defaults to 1. echo $input[$rand_keys[0]] . "\n";
● If you are picking only one entry, array_rand()echo $input[$rand_keys[1]] . "\n";
returns the key for a random entry. Otherwise, it
?>
returns an array of keys for the random entries.
This is done so that you can pick random keys
as well as values out of the array.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_walk
● Apply a user function to every member of an array
● bool array_walk ( array &$array, callback $funcname [, mixed
$userdata] )

● Returns TRUE on success or FALSE on failure.


● Applies the user-defined function funcname to each element of the array


array. Typically, funcname takes on two parameters. The array
parameter's value being the first, and the key/index second. If the
optional userdata parameter is supplied, it will be passed as the third
parameter to the callback funcname.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_walk
<?php echo "Before ...:\n"; This example will
output:
$fruits = array("d" => "lemon", "a" => array_walk($fruits, 'test_print');
"orange", "b" => "banana", "c" => "apple"); Before ...:
array_walk($fruits, 'test_alter', 'fruit');
function test_alter(&$item1, $key, $prefix) d. lemon
echo "... and after:\n";
{ a. orange
array_walk($fruits, 'test_print');
$item1 = "$prefix: $item1"; b. banana
?>
} c. apple

function test_print($item2, $key) ... and after:

{ d. fruit: lemon

echo "$key. $item2<br />\n"; a. fruit: orange

} b. fruit: banana
c. fruit: apple

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_unique
● Removes duplicate values from an array
● array array_unique ( array $array )
● array_unique() takes input array and returns a new array without
duplicate values.
● Note that keys are preserved. array_unique() sorts the values treated as
string at first, then will keep the first key encountered for every value,
and ignore all following keys. It does not mean that the key of the first
related value from the unsorted array will be kept.
● Note: Two elements are considered equal if and only if (string) $elem1
=== (string) $elem2. In words: when the string representation is the
same.
● The first element will be used.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_unique
<?php
<?php
$input = array("a" => "green", "red", "b"
$input = array(4, "4", "3", 4, 3, "3");
=> "green", "blue", "red");
$result = array_unique($input);
$result = array_unique($input);
var_dump($result);
print_r($result);
?>
?>
The above example will output:
The above example will output:
array(2) {
Array
[0] => int(4)
(
[2] => string(1) "3"
[a] => green
}
[0] => red
[1] => blue
)

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_map
● Applies the callback to the ?php
elements of the given arrays This makes $b have:
function cube($n)
● array array_map ( callback Array
{ (
$callback, array $arr1 [, array
[0] => 1
$...] ) return($n * $n * $n);
[1] => 8
● array_map() returns an array } [2] => 27
containing all the elements of [3] => 64
$a = array(1, 2, 3, 4, 5); [4] => 125
arr1 after applying the callback
$b = array_map("cube", $a); )
function to each one. The
number of parameters that the print_r($b);
callback function accepts
?>
should match the number of
arrays passed to the
array_map()

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_reduce
● Iteratively reduce the array to a single value using a callback function
● mixed array_reduce ( array $input, callback $function [, int $initial] )

<?php
function rmul($v, $w) $a = array(1, 2, 3, 4, 5);
function rsum($v, $w)
{ $x = array();
{
$v *= $w; $b = array_reduce($a, "rsum");
$v += $w;
return $v; $c = array_reduce($a, "rmul", 10);
return $v;
} $d = array_reduce($x, "rsum", 1);
}
?>
This will result in $b containing 15, $c
containing 1200 (= 10*1*2*3*4*5), and $d
containing 1.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_reduce
● array_reduce() applies iteratively the function function to the elements of
the array input, so as to reduce the array to a single value.
● If the optional initial is available, it will be used at the beginning of the
process, or as a final result in case the array is empty.
● If the array is empty and initial is not passed, array_reduce() returns
NULL.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_reverse
● Return an array with elements in reverse order
● array array_reverse ( array $array [, bool $preserve_keys] )

● array_reverse() takes input array and returns a new array with the order
of the elements reversed, preserving the keys if preserve_keys is TRUE.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_reverse
$result will be
$result_keyed will be:
Array
<?php Array
(
$input = array("php", 4.0, array("green", "red")); (
[0] => Array
$result = array_reverse($input); [2] => Array
(
$result_keyed = array_reverse($input, true); (
[0] => green
?> [0] => green
[1] => red
[1] => red
)
)
[1] => 4
This makes both $result and $result_keyed [1] => 4
have the same elements, [2] => php
[0] => php
but note the difference between the keys. )
)

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_search
● Searches the array for a given value and returns the corresponding key if
successful mixed array_search ( mixed $needle, array $haystack [, bool
$strict] )
● Searches haystack for needle and returns the key if it is found in the array,
FALSE otherwise.
● If needle is a string, the comparison is done in a case-sensitive manner.
● Prior to PHP 4.2.0, array_search() returns NULL on failure instead of
FALSE.
● If the optional third parameter strict is set to TRUE then the array_search()
will also check the types of the needle in the haystack.

<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>
www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_shift
● Shift an element off the beginning of array
● 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. If array is empty (or is not an array), NULL will be
returned.
● This function will reset() the array pointer after use.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_shift
<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack); This would result in $stack having 3 elements left:
?> Array
(
[0] => banana
[1] => apple
[2] => raspberry
)
and orange will be assigned to $fruit.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_unshift
<?php
$queue = array("orange", "banana");
● Prepend one or more elements to the
beginning of an array array_unshift($queue, "apple", "raspberry");
● int array_unshift ( array &$array, print_r($queue);
mixed $var [, mixed $...] )
?>
● array_unshift() prepends passed
elements to the front of the array. The above example will output:
Note that the list of elements is Array
prepended as a whole, so that the
(
prepended elements stay in the same
order. All numerical array keys will be [0] => apple
modified to start counting from zero [1] => raspberry
while literal keys won't be touched.
[2] => orange
● Returns the new number of elements
in the array [3] => banana
)

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_slice
● Extract a slice of the array
● rray array_slice ( array $array, int $offset [,
int $length [, bool $preserve_keys]] )

● array_slice() returns the sequence of


elements from the array array as specified by
the offset and length parameters.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_slice
● if offset is non-negative, the sequence will start at that offset in the array.
If offset is negative, the sequence will start that far from the end of the
array.
● If length is given and is positive, then the sequence will have that many
elements in it. If length is given and is negative then the sequence will
stop that many elements from the end of the array. If it is omitted, then
the sequence will have everything from offset up until the end of the
array.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_slice
<?php
$input = array("a", "b", "c", "d", "e");

Array
$output = array_slice($input, 2); // (
returns "c", "d", and "e" [0] => c
[1] => d
$output = array_slice($input, -2, 1); // )
returns "d" Array
$output = array_slice($input, 0, 3); // (
returns "a", "b", and "c" [2] => c
[3] => d
)
// note the differences in the array keys
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_splice
● Remove a portion of the array<?php and
replace it with something else$input = array("red", "green", "blue", "yellow");
● array array_splice ( array &$input,
array_splice($input, 2);
int $offset [, int $length [, array
$replacement]] ) // $input is now array("red", "green")

$input = array("red", "green", "blue", "yellow");


array_splice($input, 1, -1);
// $input is now array("red", "yellow")

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_splice
● If offset is positive then the start of removed portion is at that offset from
the beginning of the input array.
● If offset is negative then it starts that far from the end of the input array.
● If length is omitted, removes everything from offset to the end of the
array. If length is specified and is positive, then that many elements will
be removed. If length is specified and is negative then the end of the
removed portion will be that many elements from the end of the array.
Tip: to remove everything from offset to the end of the array when
replacement is also specified, use count($input) for length.
● If replacement array is specified, then the removed elements are
replaced with elements from this array. If offset and length are such that
nothing is removed, then the elements from the replacement array are
inserted in the place specified by the offset. Note that keys in
replacement array are not preserved. If replacement is just one element
it is not necessary to put array() around it, unless the element is
an array itself.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_merge
● array array_merge ( array $array1 [, This example will
<?php output:
array $array2 [, array $...]] )
● array_merge() merges the $array1 = array( Array
elements of one or more arrays "color" => "red", 2, 4); (
together so that the values of one
$array2 = array( [color] => green
are appended to the end of the
previous one. It returns the resulting "a", "b", [0] => 2
array. "color" => "green", [1] => 4
● If the input arrays have the same "shape" =>
"trapezoid",4); [2] => a
string keys, then the later value for
that key will overwrite the previous $result = [3] => b
one. If, however, the arrays contain array_merge($array1, [shape] => trapezoid
numeric keys, the later value will $array2);
[4] => 4
not overwrite the original value, but print_r($result);
will be appended. ?>
)

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_merge_recursive
Array
<?php
● If the input arrays have (
the same string keys, $ar1 =[color]
array("color"
=> Array =>
then the values for these array("favorite" => "red"), 5);
(
keys are merged together
$ar2 = array(10, "color"
[favorite] =>
=> Array
into an array, and this is array("favorite" => "green", "blue"));
done recursively, so that (
if one of the values is an $result = array_merge_recursive($ar1,
[0] => red
$ar2);
array itself, the function [1] => green
will merge it with a print_r($result);
)
corresponding entry in ?>
another array too. [0] => blue
)
[0] => 5
[1] => 10
)

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_key

● Return all the keys of an array


● array array_keys ( array $input [, mixed $search_value [,
bool $strict]] )
● array_keys() returns the keys, numeric and string, from the
input array.
● If the optional search_value is specified, then only the
keys for that value are returned. Otherwise, all the keys
from the input are returned. As of PHP 5, you can use
strict parameter for comparison including type (===).

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_key
The above example will output:
<?php
Array
$array = array(0 => 100, "color" => "red"); (
[0] => 0
print_r(array_keys($array)); [1] => color
)
Array
$array = array("blue", "red", "green", "blue", "blue"); (
[0] => 0
print_r(array_keys($array, "blue"));
[1] => 3
[2] => 4
)
$array = array("color" => array("blue", "red", "green"), Array
"size" => array("small", "medium", "large")); (
[0] => color
print_r(array_keys($array)); [1] => size
)
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_key_exists
● Checks if the given key or index exists in the array
● bool array_key_exists ( mixed $key, array $search )
● array_key_exists() returns TRUE if the given key is set in the array. key
can be any value possible for an array index. array_key_exists() also
works on objects. The name of this function is key_exists() in PHP
4.0.6.

<?php
<?php
$search_array = array('first' => null, 'second' =>
$search_array = array('first' => 1, 'second' => 4); 4);

if (array_key_exists('first', $search_array)) { // returns false

echo "The 'first' element is in the array"; isset($search_array['first']);

} // returns true
array_key_exists('first', $search_array);
?>
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_fill
● Fill an array with values ?php
– array array_fill ( int $start_index, int $a = array_fill(5, 6, 'banana');
$num, mixed $value )
print_r($a);
– array_fill() fills an array with num entries
of the value of the value parameter, ?>
keys starting at the start_index $a now is:
parameter. Note that num must be a Array
number greater than zero, or PHP will (
throw a warning. [5] => banana
[6] => banana
[7] => banana
[8] => banana
[9] => banana
[10] => banana
)

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_fill_keys
● Fill an array with values, <?php
specifying keys $keys = array('foo', 5, 10, 'bar');
● array array_fill_keys ( array
$a = array_fill_keys($keys, 'banana');
$keys, mixed $value )
● array_fill_keys() fills an array print_r($a);
with the value of the value ?>
parameter, using the values of
$a now is:
the keys array as keys.
Array
(
[foo] => banana
[5] => banana
[10] => banana
[bar] => banana
)

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_flip
● Exchanges all keys with their associated values in
<?php
an array
● array array_flip ( array $trans ) $trans = array("a" => 1, "b" => 1, "c"
● array_flip() returns an array in flip order, i.e. keys => 2);
from trans become values and values from trans $trans = array_flip($trans);
become keys. print_r($trans);
● Note that the values of trans need to be valid
keys, i.e. they need to be either integer or string. ?>A
warning will be emitted if a value has the wrong now $trans is:
type, and the key/value pair in question will not beArray
flipped. (
● If a value has several occurrences, the latest key [1] => b
will be used as its values, and all others will be [2] => c
)
lost.
● array_flip() returns FALSE if it fails.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_intersect
● Computes the intersection of arrays <?php
● array array_intersect ( array $array1,$array1 = array("a" => "green", "red", "blue");
array $array2 [, array $ ...] )
$array2 = array("b" => "green", "yellow", "red");
● array_intersect() returns an array
containing all the values of array1 that$result = array_intersect($array1, $array2);
are present in all the arguments. Noteprint_r($result);
that keys are preserved.
?>
– Two elements are considered
equal if and only if (string) $elem1The above example will output:
=== (string) $elem2. In words: Array
when the string representation is
(
the same.
[a] => green
[0] => red
)

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_intersect_key
● Computes the intersection of arrays using keys for
comparison
– array array_intersect_key ( array $array1, array
$array2 [, array $ ...] )
– array_intersect_key() returns an array containing
all the values of array1 which have matching
keys that are present in all the arguments.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_intersect_key
<?php
● In our example you see that only the $array1 = array('blue' => 1, 'red' => 2,
'green' => 3, 'purple' => 4);
keys 'blue' and 'green' are present in
both arrays and thus returned. Also $array2 = array('green' => 5, 'blue' => 6,
notice that the values for the keys 'blue' 'yellow' => 7, 'cyan' => 8);
and 'green' differ between the two
arrays. A match still occurs because var_dump(array_intersect_key($array1,
only the keys are checked. The values $array2));
returned are those of array1.
?>
● The two keys from the key => value
pairs are considered equal only if The above example will output:
(string) $key1 === (string) $key2 . In array(2) {
other words a strict type check is ["blue"]=>
int(1)
executed so the string representation ["green"]=>
must be the same. int(3)
}

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_intersect_uassoc
<?php
● Computes the intersection of arrays with
additional index check, compares indexes by a $array1 = array("a" => "green", "b" =>
"brown", "c" => "blue", "red");
callback function
– array array_intersect_uassoc ( array $array1, $array2 = array("a" => "GREEN", "B"
array $array2 [, array $ ..., callback => "brown", "yellow", "red");
$key_compare_func] )
– array_intersect_uassoc() returns an array
containing all the values of array1 that are present print_r(array_intersect_uassoc($array
in all the arguments. Note that the keys are used 1, $array2, "strcasecmp"));
in the comparison unlike in array_intersect(). ?>
– The index comparison is done by a user supplied
callback function. It must return an integer less
than, equal to, or greater than zero if the first
argument is considered to be respectively less
than, equal to, or greater than the second. The above example will output:
Array
(
[b] => brown
)
www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_intersect_assoc
<?php
● Computes the intersection of arrays $array1 = array("a" => "green", "b" =>
with additional index check "brown", "c" => "blue", "red");
● array array_intersect_assoc ( array
$array2 = array("a" => "green", "yellow",
$array1, array $array2 [, array $ "red");
...] )
$result_array =
● array_intersect_assoc() returns an array_intersect_assoc($array1, $array2);
array containing all the values of
array1 that are present in all the print_r($result_array);
arguments. Note that the keys are ?>
used in the comparison unlike in The above example will output:
array_intersect().
Array
(
[a] => green
)

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_intersect_assoc
● In our example you see that only the pair "a" => "green" is present in
both arrays and thus is returned. The value "red" is not returned
because in $array1 its key is 0 while the key of "red" in $array2 is 1.
● The two values from the key => value pairs are considered equal only if
(string) $elem1 === (string) $elem2 . In other words a strict type check is
executed so the string representation must be the same.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_intersect_ukey
● Computes the intersection of arrays using a callback function on the
keys for comparison
● array array_intersect_ukey ( array $array1, array $array2 [, array $...,
callback $key_compare_func] )
● array_intersect_ukey() returns an array containing all the values of
array1 which have matching keys that are present in all the arguments.
● This comparison is done by a user supplied callback function. It must
return an integer less than, equal to, or greater than zero if the first key
is considered to be respectively less than, equal to, or greater than the
second.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_intersect_ukey
$array1 = array('blue' => 1, 'red' => 2, 'green' => 3,
<?php
'purple' => 4);
function key_compare_func($key1, $key2)
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7,
{ 'cyan' => 8);

if ($key1 == $key2)
return 0; var_dump(array_intersect_ukey($array1, $array2,
'key_compare_func'));
else if ($key1 > $key2)
?>
return 1;
else
return -1; The above example will output:
} array(2) {
["blue"]=>
int(1)
["green"]=>
int(3)
}
www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_uintersect
<?php
● Computes the intersection of $array1 = array("a" => "green", "b" => "brown",
arrays, compares data by a
callback function "c" => "blue", "red");
● array array_uintersect ( array
$array2 = array("a" => "GREEN",
$array1, array $array2 [, array
"B" => "brown", "yellow", "red");
$ ..., callback
$data_compare_func] )
● array_uintersect() returns anprint_r(array_uintersect($array1, $array2, "strcasecmp"));
array containing all the values
?>
of array1 that are present in
all the arguments. The dataTheis above example will output:
compared by using a callback Array
(
function. [a] => green
[b] => brown
[0] => red
)

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_uintersect_assoc
● Computes the intersection of arrays <?php
with additional index check, $array1 = array("a" => "green", "b" =>
compares data by a callback "brown", "c" => "blue", "red");
function $array2 = array("a" => "GREEN", "B" =>
● rray array_uintersect_assoc ( array "brown", "yellow", "red");
$array1, array $array2 [, array $ ...,
callback $data_compare_func] )
● print_r(array_uintersect_assoc($array1,
$array2, "strcasecmp"));
● array_uintersect_assoc() returns an
array containing all the values of ?>
array1 that are present in all the The above example will output:
arguments. Array
(
[a] => green
)

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_uintersect_uassoc
<?php
● Computes the intersection of arrays with
additional index check, compares data and $array1 = array("a" => "green", "b" => "brown", "c"
indexes by a callback functions => "blue", "red");
● array array_uintersect_uassoc ( array
$array1, array $array2 [, array $ ..., $array2 = array("a" => "GREEN", "B" => "brown",
callback $data_compare_func, callback "yellow", "red");
$key_compare_func] )

● array_uintersect_uassoc() returns an array print_r(array_uintersect_uassoc($array1, $array2,


containing all the values of array1 that are "strcasecmp", "strcasecmp"));
present in all the arguments. Note that the
keys are used in the comparison unlike in ?>
array_uintersect(). The above example will output:
Array
(
[a] => green
[b] => brown
)

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_diff
● Computes the difference of arrays <?php
– array array_diff ( array $array1,
$array1 = array("a" => "green", "red", "blue", "red");
array $array2 [, array $ ...] )
– array_diff() returns an array $array2 = array("b" => "green", "yellow", "red");
containing all the values of $result = array_diff($array1, $array2);
array1 that are not present in
any of the other arguments.
print_r($result);
Note that keys are preserved.
?>

This will output :


Array
(
[1] => blue
)

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_diff_key
● Computes the difference of arrays using keys for comparison
– array array_diff_key ( array $array1, array $array2 [, array $ ...] )
● array_diff_key() returns an array containing all the values of array1 that
have keys that are not present in any of the other arguments. Note that
the associativity is preserved. This function is like array_diff() except the
comparison is done on the keys instead of the values.
– The two keys from the key => value pairs are considered equal only if (string)
$key1 === (string) $key2 . In other words a strict type check is executed so the
string representation must be the same.

<?php
$array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4); This example will output
array(2) {
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan' => 8); ["red"]=>
int(2)
["purple"]=>
var_dump(array_diff_key($array1, $array2)); int(4)
}
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_diff_assoc
● Computes the difference of arrays with additional index check
– array array_diff_assoc ( array $array1, array $array2 [, array $ ...] )
– array_diff_assoc() returns an array containing all the values from array1
that are not present in any of the other arguments.
<?php– Note that the keys are used in the comparison unlike array_diff().
$array1 = array("a" => "green", "b" =>
"brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", This example will
"red"); output:
$result = array_diff_assoc($array1, Array
$array2); (
[b] =>
print_r($result); brown
?> [c] =>
blue
[0] => red
)

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_udiff
● Computes the difference of arrays by using a callback function for data
comparison
● array array_udiff ( array $array1, array $array2 [, array $ ..., callback
$data_compare_func] )

● array_udiff() returns an array containing all the values of array1 that are
not present in any of the other arguments. Note that keys are preserved.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_diff_uassoc
● Computes the difference of arrays with additional index check which is
performed by a user supplied callback function
– array_diff_uassoc() returns an array containing all the values from array1
that are not present in any of the other arguments.
<?php
function key_compare_func($a, $b)
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
{
$array2 = array("a" => "green", "yellow", "red");
if ($a === $b) {
$result = array_diff_uassoc($array1, $array2, "key_compare_func");
return 0;
print_r($result);
}
?>
return ($a > $b)? 1:-1; The above example will output:
Array
}
(
[b] => brown
[c] => blue
[0] => red
)
www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_diff_uassoc
● Note that the keys are used in the comparison unlike array_diff().
– This comparison is done by a user supplied callback function. It
must return an integer less than, equal to, or greater than zero if the
first argument is considered to be respectively less than, equal to, or
greater than the second.
– This is unlike array_diff_assoc() where an internal function for
comparing the indices is used.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_diff_ukey
● Computes the difference of arrays using a callback function on the keys
for comparison
– array array_diff_ukey ( array $array1, array $array2 [, array $ ...,
callback $key_compare_func] )
● array_diff_ukey() returns an array containing all the values of
array1 that have keys that are not present in any of the other
arguments. Note that the associativity is preserved. This function
is like array_diff() except the comparison is done on the keys
instead of the values.
● This comparison is done by a user supplied callback function. It

must return an integer less than, equal to, or greater than zero if
the first key is considered to be respectively less than, equal to,
or greater than the second.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_diff_ukey
<?php $array1 = array('blue' => 1, 'red' => 2,
'green' => 3, 'purple' => 4);
function
key_compare_func($key1 $array2 = array('green' => 5, 'blue' => 6,
, $key2) 'yellow' => 7, 'cyan' => 8);

{
if ($key1 == $key2) var_dump(array_diff_ukey($array1,
$array2, 'key_compare_func'));
return 0;
?>
else if ($key1 > $key2)
return 1;
else The above example will output:
array(2) {
return -1;
["red"]=>
} int(2)
["purple"]=>
int(4)
}

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_udiff_assoc
● Computes the difference of arrays with additional index check,
compares data by a callback function
● array array_udiff_assoc ( array $array1, array $array2 [, array $ ...,
callback $data_compare_func] )
● array_udiff_assoc() returns an array containing all the values from
array1 that are not present in any of the other arguments.
● Note that the keys are used in the comparison unlike array_diff() and
array_udiff(). The comparison of arrays' data is performed by using an
user-supplied callback.
● In this aspect the behaviour is opposite to the behaviour of
array_diff_assoc() which uses internal function for comparison.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

array_udiff_uassoc
● Computes the difference of arrays with additional index check,
compares data and indexes by a callback function
● array array_udiff_uassoc ( array $array1, array $array2 [, array $ ...,
callback $data_compare_func, callback $key_compare_func] )
● array_udiff_uassoc() returns an array containing all the values from
array1 that are not present in any of the other arguments. Note that the
keys are used in the comparison unlike array_diff() and array_udiff().

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Modifying Arrays
● Array elements operate just like regular
scalar variables using operators
● Don't put quotes around element key when
interpolating array elements in strings
● If array key has whitespace or other
punctuation, use curly braces

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Modifying Arrays
● Use unset() to remove elements from array
● Use implode() to quickly print all array values
as a string
● Use explode() to turn a string into an array

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Sorting Arrays
● Use sort() only on numeric arrays, because it
resets the keys of the array when it sorts
● Use asort() to sort an associative array
● Use ksort() to sort arrays by key
● The reverse sorting functions are rsort(),
arsort() and krsort()

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Using Multidimensional Arrays


● Use array() construct to create arrays that
have more arrays as element values
● Access element in multidimensional arrays
by using more sets of square brackets to
identify elements
● Use nested foreach() to iterate through each
dimension of a multidimensional array

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Understanding the components of an array:
elements, keys and values
● Defining an array in your programs two
ways: with array() and with square brackets
● Understanding the shortcuts PHP provide for
arrays with numeric keys
● Counting the number of elements in array

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Visiting each element of array with foreach()
● Modifying array element values inside a
foreach() code block
● Visiting each element of a numeric key with
for()
● Understanding the order in which foreach()
and for() visit array elements

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Checking for an array element with a
particular key
● Checking for an array element with a
particular value
● Interpolating array element values in strings
● Removing an element from an array
● Generating a string from array with implode()
● Generating array from string with explode()

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Sorting an array with sort(), asort(), or ksort()
● Sorting an array in reverse
● Defining a multidimensional array
● Accessing individual elements of a
multidimensional array
● Visiting each element in a multidimensional
array with foreach() or for()
● Interpolating multidimensional array
elements

www.intellibitz.com training@intellibitz.com
CHAPTER 5

FUNCTIONS

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Functions
● Declaring and Calling Functions
● Passing Arguments to Functions
● Returning Values from Functions
● Understanding Variable Scope

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Functions
● Functions allows you to reuse code
● Functions are named set of statements that
you can execute by invoking the function
name instead of retyping the statements
● Functions can take arguments as well return
value
● Variables inside a function and outside a
function live in two separate worlds

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Declaring and Calling Functions


● Function names follow the same rules as
variable names
● Functions can be defined before or after they
are called
● Avoid using the same name for a function
and a variable

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming

Passing Arguments to
TD_PHP_V1.0.0

Functions
● The input values supplied to a function are
called arguments
● Functions can take optional argument by
specifying a default in the declaration
● Optional arguments must come after
mandatory arguments
● Default values for arguments must be literals,
and not variables

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming

Passing Arguments to
TD_PHP_V1.0.0

Functions
● Changes made to a variable passed as an
argument don't affect the variable outside the
function
● Modifying arguments doesn't affect variables
outside the function even if the argument has
the same name as a variable outside the
function

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming

Returning values from


TD_PHP_V1.0.0

Functions
● Functions can also compute a value, called
the return value
● Return value of a function can be used in
assignment just like number or a string
● To return more than one value from a
function, use an array as return value
● A test expression can consist just a function
call with no comparison or other operator

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Understanding Variable Scope


● Variables defined outside of a function are
called global variables
● Variables defined inside of a function are
called local variables
● Global variables can be accessed from
inside a function, but local variables of a
function are not accessible outside that
function

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Understanding Variable Scope


● Two ways to access a global variable from
inside a function: use $GLOBALS
● Use the global keyword to “bring a variable
into local scope” inside the function
● $GLOBALS is a special kind of pre-defined
variable, called an auto-global
● The auto-globals are always arrays that are
automatically populated with data

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Defining your own functions and calling them
in your programs
● Defining a function with mandatory
arguments
● Defining a function with optional arguments
● Returning a value from a function
● Understanding variable scope
● Using global variables inside a function

www.intellibitz.com training@intellibitz.com
CHAPTER 6

HTML AN INTRODUCTION TO
WEB FORMS

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

HTML
● HTML stands for Hyper Text Markup
Language
● An HTML file is a text file containing small
markup tags
● The markup tags tell the Web browser how
to display the page

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

HTML File
● An HTML file must have an htm or html file
extension
● An HTML file can be created using a simple
text editor
● The html files are viewed in a web browser.
● Fire fox, Internet Explorer,Netscafe, opera
are few well known web browsers.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Viewing outputs in browsers


● To view the output, correct path of the html
file has to be typed into the address box of
the web browser .
● The web browser has to be refreshed to view
the changes made in the html file

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

HTML Tags
● The tags in HTML are enclosed by angle
brackets(<,>).
● Html tags normally come in pair s like
<b></b>.
● Html tags are not case sensitive ,<b>means
the same as <B>.
● <html> </html> are the starting and ending
tags.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Head
● Html files has two major parts,head and
body.
● <title> </title>tags are the major tag used
with in <head></head> tags
● <title> tag tells the browser what has to be
displayed in the title bar of the web browser.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Formatting
● <strong> Defines strong text
● <sub> Defines subscripted text
● <sup> Defines superscripted text
● <ins> Defines inserted text
● <del> Defines deleted text
● <s> Deprecated. Use <del> instead
● <strike> Deprecated. Use <del> instead
● <u> Deprecated. Use styles instead

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

BODY
● <BODY> encloses the content that has to be
displayed in the browser.
● <p> tag encloses the paragraph.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Attribute
● Attributes provide additional information to an
HTML element.
● Attributes always come in name/value pairs
like this: name="value".
● Attributes are always specified in the start
tag of an HTML element.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Attribute
● The following tag defines an HTML table:
<table>. With an added border attribute, you
can tell the browser that the table should
have no borders: <table border="0">
● Attribute values should always be enclosed
in quotes. Double style quotes are the most
common, but single style quotes are also
allowed.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Attribute
● In some rare situations, like when the
attribute value itself contains quotes, it is
necessary to use single quotes:
– name='John "ShotGun" Nelson'

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Headings
● Headings are defined with the <h1> to <h6>
tags. <h1> defines the largest heading. <h6>
defines the smallest heading.
● Paragraphs are defined with the <p> tag.
● HTML automatically adds an extra blank line
before and after a headings and paragraph.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Line break
● The <br> tag is used when you want to end a
line, but don't want to start a new paragraph.
The <br> tag forces a line break wherever
you place it.
● The <br> tag is an empty tag. It has no
closing tag.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Comments
● The comment tag is used to insert a comment in
the HTML source code. A comment will be ignored
by the browser. You can use comments to explain
your code, which can help you when you edit the
source code at a later date.
● <!-- This is a comment -->
● Note that you need an exclamation point after the
opening bracket, but not before the closing
bracket.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Formatting
● HTML defines a lot of elements for formatting
output, like bold or italic text.
● <b> Defines bold text
● <big> Defines big text
● <em> Defines emphasized text
● <i> Defines italic text
● <small> Defines small text

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Formatting
● <code> Defines computer code text
● <kbd> Defines keyboard text
● <samp> Defines sample computer code
● <tt> Defines teletype text
● <var> Defines a variable
● <pre> Defines preformatted text
● <listing> Deprecated. Use <pre> instead
● <plaintext> Deprecated. Use <pre> instead
● <xmp> Deprecated. Use <pre> instead

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Formatting
● <abbr> Defines an abbreviation
● <acronym> Defines an acronym
● <address> Defines an address element
● <bdo> Defines the text direction
● <blockquote> Defines a long quotation
● <q> Defines a short quotation
● <cite> Defines a citation
● <dfn> Defines a definition term

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Html entities
● Some characters like the < character, have a
special meaning in HTML, and therefore
cannot be used in the text.
● To display a less than sign (<) in HTML, we
have to use a character entity.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Html entities
● A character entity has three parts: an
ampersand (&), an entity name or a # and an
entity number, and finally a semicolon (;).
– To display a less than sign in an HTML
document we must write: &lt; or &#60;

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Html entities
● Normally HTML will truncate spaces in your
text. If you write 10 spaces in your text HTML
will remove 9 of them.
● To add spaces(non breaking space) to your
text, use the &nbsp; character entity.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Html entities
● non-breaking space &nbsp; &#160;
● < less than &lt; &#60;
● > greater than &gt; &#62;
● & ampersand &amp; &#38;
● " quotation mark &quot; &#34;
● ' apostrophe &apos; &#39;

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Html entities
● ¢ cent &cent; &#162;
● £ pound &pound; &#163;
● ¥ yen &yen; &#165;
● § section &sect; &#167;
● © copyright &copy; &#169;
● ® registered trademark &reg; &#174;
● × multiplication &times; &#215;
● ÷ division &divide; &#247;

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Links
● HTML uses a hyperlink to link to another
document on the Web.
● The <a> tag is used to create an anchor to
link from, the href attribute is used to address
the document to link to, and the words
between the open and close of the anchor
tag will be displayed as a hyperlink.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Link
● With the target attribute, you can define
where the linked document will be opened.

● <a href="http://www.IntelliBitz.com/"
● target="_blank">Visit IntelliBitz!</a>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Link
● The name attribute is used to create a
named anchor.
● When using named anchors we can create
links that can jump directly into a specific
section on a page, instead of letting the user
scroll around to find what he/she is looking
for.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Frames
● With frames, you can display more than one
Web page in the same browser window.
● The disadvantages of using frames are:
– The web developer must keep track of more
HTML documents
– It is difficult to print the entire page

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Frames
● The <frameset> tag defines how to divide
the window into frames
● Each frameset defines a set of rows or
columns
● The values of the rows/columns indicate the
amount of screen area each row/column will
occupy

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Frames
● The <frame> tag defines what HTML
document to put into each frame

<frameset cols="25%,75%">
<frame src="frame_a.htm">
<frame src="frame_b.htm">
</frameset>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Frames
● if you add a <noframes> tag containing some
text for browsers that do not support frames,
you will have to enclose the text in
<body></body> tags!

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Tables
● Tables are defined with the <table> tag.
● A table is divided into rows (with the <tr>
tag)
● Each row is divided into data cells (with the
<td> tag).
● A data cell can contain text, images, lists,
paragraphs, forms, horizontal rules, tables,
etc.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Tables
<table border="1"> <table border="1">
<tr> <tr>
<td>row 1, cell 1</td> <th>Heading</th>
<td>row 1, cell 2</td> <th>Another Heading</th>
</tr> </tr>
<tr> <tr>
<td>row 2, cell 1</td> <td>row 1, cell 1</td>
<td>row 2, cell 2</td> <td>row 1, cell 2</td>
</tr> </tr>
</table> <tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

List
● An unordered list is a list of items. The list
items are marked with bullets (typically small
black circles).
● An ordered list is also a list of items. The list
items are marked with numbers.
● A definition list is not a list of items. This is a
list of terms and explanation of the terms.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

List

<dl>
<ul> <ol> <dt>Coffee</dt>
<li>Coffee</li> <li>Coffee</li> <dd>Black hot drink</dd>
<li>Milk</li> <li>Milk</li> <dt>Milk</dt>
</ul> </ol> <dd>White cold drink</dd>
</dl>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Image
● With HTML you can display images in a
document.
● The src attribute of img tag should be
assigned with the path of the file.
● Img tag has no closing tag.

<img src="boat.gif" alt="Big Boat">

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Image
● The "alt" attribute tells the reader what he or
she is missing on a page if the browser can't
load images.
● The browser will then display the alternate
text instead of the image.
● It is a good practice to include the "alt"
attribute for each image on a page, to
improve the display

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Background
● The <body> tag has two attributes where you
can specify backgrounds.
– The bgcolor attribute specifies a background-
color for an HTML page.
– The background attribute specifies a
background-image for an HTML page.
● The background can be a color or an image.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

<div> <span>
● A <div> is a block value element ,that is
there is a physical break
● between it and elements above and below it
● A <span> isn't block level instead its inline so
you can apply it to for instance a single
phrase within a sentence.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Web form
● Web form are used to get data from the
user.
● Form elements are elements that allow the
user to enter information (like text fields,
textarea fields, drop-down menus, radio
buttons, checkboxes, etc.) in a form.

www.intellibitz.com training@intellibitz.com
www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

<form> tag
● <form> tag serves to define the section of
HTML document that contain form fields
● Attributes
– Action
● The URL that the form is submitted to
– Method
● The method under which the form is submitted(GET or
POST)
– Enctype
● The encoding type to use(miltipart/formdata).

www.intellibitz.com training@intellibitz.com
www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Text box
● Text box is a single line text field.
● <input type = “text”> tag can be used to
define a textbox
● Attributes
– Name
● The name assigned to the textbox.this will be the key
to $_POST[ ] .
– Size
● The size of the text fields in browser in character.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Textbox
– Maxlength
● The maximum number of character to accept in the
textfields.
– Value
● The default value of the textbox.
● This value will be displayed inside the textbox on the
browser.

<input type = “text”


name = “mytextfield”
value = “my default value”
size = 30
maxlength = 30>
www.intellibitz.com training@intellibitz.com
www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Password fields
● Password field masks the input so that it
cannot be read on the screen.
● The attributes of password field are same as
text field.

<input type = “password”


name = “mypassword”
value = “you cannot read this on browser”>

www.intellibitz.com training@intellibitz.com
www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Option button
● Option button allows the user to select the
single item from the list of options.
● The option button can be created in HTML
can be created by setting type attribute of
<input> tag to radio
● For a group of option buttons to function
properly,the name attribute of option button
must have the same value.

www.intellibitz.com training@intellibitz.com
www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Option button
● The value attribute will not be diaplayed in
the browser but but instead the value
submitted when the form is submitted.
● The checked value will be the default
selected value and only one checked
attribute can exist .

<input type = “radio” name = “myradio” checked value = “1”>Football<br>


<input type = “radio” name = “myradio” value = “1”>Soccer<br>
<input type = “radio” name = “myradio” value = “1”>Hockey<br>
<input type = “radio” name = “myradio” value = “1”>Baseballl<br>
www.intellibitz.com training@intellibitz.com
www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Check box
● The check box allows the user to select the
any number of the provided option.
● Unlike an option button it is not required that
each check box require same name and
there is no restriction on how many checked
value can exist

<input type = “checkbox” name = “mycheckbox1” checked value = “1”>Football<br>


<input type = “checkbox” name = “mycheckbox2” value = “1”>Soccer<br>
<input type = “checkbox” name = “mycheckbox3” checked value = “1”>Hockey<br>
<input type = “checkbox” name = “mycheckbox4” value = “1”>Baseballl<br>
www.intellibitz.com training@intellibitz.com
www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Lists and drop-down lists


● Lists
– A list can be in a standard scrollable box where
one or more items can be selected.
● Drop-down lists
– A list can be displayed as single line and user
clicks the arrow button to see all the choices

www.intellibitz.com training@intellibitz.com
www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Lists and drop-down lists


● A <select> tag defines a list.
● Attributes
– Name
● The name given to the list.
– Size
● The number of items to display at once in the lists (a
value of one indicates a dropdown lists).
– Multiple
● A flag indicating whether multiple items can be
selected

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Lists and drop-down lists


● <option> tag is used to represent items in the
lists
● Attributes
– Value
● The value to submit if selected.
– Selected
● A flag indicating if this item is selected by default.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Lists and drop-down lists

Drop down box


<select name = “colors” size = 1>
<option value = “red” >I like Red </option>
<option value = “blue” > I like Blue</option>
<option value = “green”> I like Green</option>
</select>

List box
<select name = “colors” size = 4 multiple>
<option value = “chinese” >I like chinese food </option>
<option value = “Mexican” > I like mexican food</option>
<option value = “American”> I like American Food</option>
<option value = “Italian “> I like Italian food</option>
</select>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

submit
● For any form data to be sent from client to
server it must be submitted.
● Submit defines a button which enables the
user to submit a form.

<input type = “submit”


value = “This is the default submit button”
name = “mysubmit”>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Image
● <input type = “image”> is identical to
<input type = “submit”>except thet instead of
displaying a button it displays a specific
image.

<input type = “image “


src = “/images/mybutton.gif”
name = “myimgebutton”>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Hidden
● Along with user editable data,HTML also
allows to send uneditable hidden data to the
server.

<input type = “hidden” name = “myvalue” value = “foo”>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Textarea
● Textarea is the multiline text field.
● Attributes
– Name
● Name of the field
– Cols
● Number of columns wide (in characters)of the text field
– Rows
● Number of rows long

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Textarea
– Wrap
● Determines how the text should be submitted in
relation to how it was typed in text area
● Wrap attribute accepts one of the following
values
– Off
● The text field will not wrap at all.
● It will run past the edge of the text field.
● Text will be sent exactly as typed.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Textarea
– Soft
● Text will be wrap to text field but sent exactly as typed
– Hard
● Text will wrap to text field
● The submission will contain new character at every
wrapping point.

<textarea rows = “5” cols = “30” wrap = “hard”> This is my text area </textarea>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

File upload
● <input type = “file”> tag allows the client
browser(user) to browse the local file system
and select a file to uplooad to the web
server.
● Attributes
– Name
● Name of the file field
– Size
● Size of the file field (in characters)
– Maxlength
● Maximum length of the text field

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Summary
● HTML is the universal markup language for
the Web.
● HTML lets you format text, add graphics,
create links, input forms, frames and tables,
etc., and save it all in a text file that any
browser can read and display.
● The key to HTML is the tags, which indicates
what content is coming up.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

CHAPTER 7

PHP AND WEB FORMS

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Making Web Forms


● Useful Server Variables
● Accessing Form Parameters
● Form Processing with Functions
● Validating Data
● HTML and JavaScript
● Displaying Default Values
● Putting it all together

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Making Web Forms


● Forms are how users communicate with your
web server.
● $_GET and $_POST auto global array
● $_SERVER holds request and server
information.
● Beware of submitted form parameter, can
contain embedded HTML or JavaScript.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Accessing Form Parameters


● A form element with multiple values needs to
have a name that ends in []
● Forms can be made flexible by putting the
display code and processing code in
separate functions
● Data validation is also made easy by using
form processing functions

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Validating Data
● Use regular expressions to match text
patterns.
● Take advantage of the fact that an empty
array evaluates to false.
● Use strlen() when checking a required.
element instead of testing the value itself in
an if() statement.
● Use intval() and floatval() to ensure number.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Validating Form Data


● Use trim() when validating string elements.
● Beware of making changes to $_POST auto-
global inside your validation functions.
● Use arrays for display and validation of
<select> menus.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

HTML and JavaScript


● Beware of cross-site scripting attack
● To prevent cross-site scripting attacks, never
display unmodified external input.
● Use strip_tags() and htmlentities().
● Always use htmlentities() to sanitize external
input use strip_tags() only when you are
absolutely sure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Displaying Default Values


● Use default values to display prepopulated
form.
● Use the previous values entered by user to
redisplay a form because of an error
● For <select> menus, add a check to the loop
that prints out the <option> tags that prints a
selected=”selected” attribute when
appropriate.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Putting It All Together


● Displaying a form, including default values
● Validating the submitted data.
● Redisplaying, the form with error messages
and preserved user input if the submitted
data isn't valid.
● Processing the submitted data if it is valid.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Understanding the conversation between the
web browser and web server that displays a
form, processes the submitted form
parameters, and then displays a result
● Making the connection between the <form>
tag's action attribute and the URL to which
form parameters are submitted

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Using values from the $_SERVER auto-
global array
● Accessing submitted form parameters in the
$_GET and $_POST auto-global arrays
● Accessing multivalued submitted form
parameters
● Using show_form(), validate_form(), and
process_form() functions for form handling

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Using a hidden form element to check
whether a form has been submitted
● Displaying error messages with a form
● Validating form elements: required elements,
integers, floating-point numbers, strings, date
ranges, email addresses, and <select>
menus

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Removing submitted HTML and JavaScript
before displaying it.
● Displaying default values for form elements.
● Using helper functions to display form
elements.

www.intellibitz.com training@intellibitz.com
CHAPTER 8

PHP AND DATABASE

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Databases
● Organizing Data in a Database
● Connecting to a Database Program
● Putting Data into the Database
● Inserting Form Data Safely
● Generating Unique ID's
● A Complete Data Insertion Form
● Retrieving Data from a Database
● MySQL without PEAR DB

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

PEAR DB
● PEAR DB is an add-on to PHP that simplifies
communication between PHP and Database
● PEAR (PHP Extension and Application
Repository) is a collection of useful modules
and libraries for PHP
● DB module is one of the most popular PEAR
modules and is bundled with PHP

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Organizing Data in a Database


● Information in your database is organized in
tables, which have rows and columns
● Tables are like Spreadsheet, except the rows
in a database table have no inherent order
● SQL is a language to ask questions of and
give instruction to the database program
● SQL keywords are not case sensitive
● INSERT, UPDATE, DELETE, SELECT

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Connecting to a Database
● Use require 'DB.php';
● Use include in place of require if you want
strict checking
● DSN is passed to DB::connect ()
● $db = DB::connect ('
db://user:pass@host/schema');
● DB::isError () checks if object contains error
information

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Creating a Table
● CREATE TABLE dishes (
● dish_id INT,
● dish_name VARCHAR(255),
● price DECIMAL(4,2),
● is_spicy INT
● )
● DROP TABLE dishes

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Putting Data into Database


● Pass an INSERT statement to the object's
query() function
● $q = $db->query(“INSERT here...”);
● Use setErrorHandling() to have your program
automatically print an error message and exit
if a query fails

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Inserting Form Data Safely


● Beware of SQL injection attack
● Some databases let you pass multiple
queries seperated by semicolons in one call
of query()
● Escape special characters (apostrophe)
● PEAR DB provides a helpful feature called
placeholders

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Generating Unique IDs


● To identify individual database records, give
them each a unique identifier
● PEAR DB helps you generate unique integer
Ids with its support for sequences
● Use nextID() to get the next value from a
sequence

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Retrieving Data from Database


● Use fetchRow() to get the next row returned
from the query, when no rows left,
fetchRow() returns false
● Use numrows() to find number of rows
returned by a SELECT query
● Wildcards _ matches one character and the
% sign matches any number including zero

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

MySQL without PEAR DB


● A program that uses the built-in PHP
functions tailored to a particular database is
faster than the one that uses PEAR DB
● For database access without PEAR DB,
mysqli extension can be used
● $db = mysqli_connect ('db.intellibitz.com',
'user', 'pass', 'schema');

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Figuring out what kinds of information belong
in a database
● Understanding how data is organized in a
database
● Loading an external file with require
● Establishing a database connection
● Creating a table in the database
● Removing a table from the database

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Using the SQL INSERT command
● Inserting data into the database with query ()
● Checking for database errors with
DB::isError()
● Setting up automatic error handling with
setErrorHandling()
● Using the SQL UPDATE and DELETE
commands

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Changing or deleting data with query()
● Counting the number of rows affected by a
query
● Using placeholders to insert data safely
● Generating unique ID values with sequences
● Using the SQL SELECT command
● Retrieving data from the database with
query() and fetchRow()

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Counting the number of rows retrieved by
query()
● Retrieving data with getAll(), getRow(), and
getOne()
● Using the SQL ORDER BY and LIMIT
keywords with SELECT
● Retrieving rows as string-keyed arrays or
objects

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Using the SQL wildcards with LIKE % and _
● Escaping SQL wildcards in SELECT
● Saving submitted form parameters in the
database
● Using data from the database in form
elements
● Using the mysqli functions instead of PEAR
DB

www.intellibitz.com training@intellibitz.com
CHAPTER 9

PHP AND MySQL FUNCTIONS

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_query
● Send a MySQL query
● resource mysql_query ( string $query [, resource
$link_identifier] )
● mysql_query() sends an unique query (multiple queries are
not supported) to the currently active database on the server
that's associated with the specified link_identifier.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_query
● Parameters
– query
● A SQL query

● The query string should not end with a semicolon.

– link_identifier
● The MySQL connection. If the link identifier is not

specified, the last link opened by mysql_connect() is


assumed. If no such link is found, it will try to create
one as if mysql_connect() was called with no
arguments. If by chance no connection is found or
established, an E_WARNING level warning is
generated.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_query
● Return Values
● For SELECT, SHOW, DESCRIBE or EXPLAIN statements,
mysql_query() returns a resource on success, or FALSE on error.
● For other type of SQL statements, UPDATE, DELETE, DROP, etc,
mysql_query() returns TRUE on success or FALSE on error.
● The returned result resource should be passed to mysql_fetch_array(),
and other functions for dealing with result tables, to access the returned
data.
● Use mysql_num_rows() to find out how many rows were returned for a
SELECT statement or mysql_affected_rows() to find out how many rows
were affected by a DELETE, INSERT, REPLACE, or UPDATE
statement.
● mysql_query() will also fail and return FALSE if the user does not have
permission to access the table(s) referenced by the query.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_result
● Get result data
● string mysql_result ( resource $result, int $row [, mixed $field]
)
● Retrieves the contents of one cell from a MySQL result set.
● When working on large result sets, you should consider using
one of the functions that fetch an entire row (specified below).
As these functions return the contents of multiple cells in one
function call, they're MUCH quicker than mysql_result(). Also,
note that specifying a numeric offset for the field argument is
much quicker than specifying a fieldname or
tablename.fieldname argument.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_result
● Parameters
– result
● The result resource that is being evaluated. This result

comes from a call to mysql_query().


– row
● The row number from the result that's being retrieved.
Row numbers start at 0.
– field
● The name or offset of the field being retrieved.

● It can be the field's offset, the field's name, or the field's table
dot field name (tablename.fieldname). If the column name has
been aliased ('select foo as bar from...'), use the alias instead of
the column name. If undefined, the first field is retrieved.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_result
<?php
● Return Values
● The contents $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');

of one cell if (!$link) {


from a MySQL die('Could not connect: ' . mysql_error());
result set on }
success, or $result = mysql_query('SELECT name FROM work.employee');
FALSE on if (!$result) {
failure. die('Could not query:' . mysql_error());
}
echo mysql_result($result, 2); // outputs third employee's name
mysql_close($link);
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_selest_db
● Select a MySQL database
● bool mysql_select_db ( string $database_name [, resource
$link_identifier] )
● Sets the current active database on the server that's
associated with the specified link identifier. Every subsequent
call to mysql_query() will be made on the active database.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_select_db
● Parameters
– database_name
● The name of the database that is to be selected.

– link_identifier
● The MySQL connection. If the link identifier is not

specified, the last link opened by mysql_connect() is


assumed. If no such link is found, it will try to create
one as if mysql_connect() was called with no
arguments. If by chance no connection is found or
established, an E_WARNING level warning is
generated.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_select_db
● Return Values
<?php
● Returns TRUE on
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
success or FALSE
if (!$link) {
on failure.
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_affected_rows
● mysql_affected_rows — Get number of affected rows in
previous MySQL operation
● int mysql_affected_rows ( [resource $link_identifier] )
● Get the number of affected rows by the last INSERT,
UPDATE, REPLACE or DELETE query associated with
link_identifier.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_affected_rows
● Parameters
● link_identifier
– The MySQL connection. If the link identifier is not specified, the last
link opened by mysql_connect() is assumed. If no such link is found,
it will try to create one as if mysql_connect() was called with no
arguments. If by chance no connection is found or established, an
E_WARNING level warning is generated.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_affected_rows
● Return Values
● Returns the number of affected rows on success, and -1 if the last query
failed.
● If the last query was a DELETE query with no WHERE clause, all of the
records will have been deleted from the table but this function will return
zero with MySQL versions prior to 4.1.2.
● When using UPDATE, MySQL will not update columns where the new
value is the same as the old value. This creates the possibility that
mysql_affected_rows() may not actually equal the number of rows
matched, only the number of rows that were literally affected by the
query.
● The REPLACE statement first deletes the record with the same primary
key and then inserts the new record. This function returns the number of
deleted records plus the number of inserted records.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_affected_row
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
} /* with a where clause that is never true, it should return
0 */
mysql_select_db('mydb');
mysql_query('DELETE FROM mytable WHERE 0');
printf("Records deleted: %d\n", mysql_affected_rows());
/* this should return the correct numbers of deleted records */
?>
mysql_query('DELETE FROM mytable WHERE id < 10');
The above example will output something similar to:
printf("Records deleted: %d\n", mysql_affected_rows()); Records deleted: 10
Records deleted: 0

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_affected_rows
<?php
/* Update records */
$link = mysql_connect('localhost', 'mysql_user',
'mysql_password'); mysql_query("UPDATE mytable SET used=1 WHERE id
< 10");
if (!$link) {
printf ("Updated records: %d\n", mysql_affected_rows());
die('Could not connect: ' . mysql_error());
mysql_query("COMMIT");
}
?>
mysql_select_db('mydb');
The above example will output something similar to:
Updated Records: 10

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_change_user
● mysql_change_user — Change logged in user of the active
connection
● int mysql_change_user ( string $user, string $password [,
string $database [, resource $link_identifier]] )
● mysql_change_user() changes the logged in user of the
current active connection, or the connection given by the
optional link_identifier parameter. If a database is specified,
this will be the current database after the user has been
changed. If the new user and password authorization fails,
the current connected user stays active.
● This function is deprecated and no longer exists in PHP.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_change_user
● Parameters
● user
● The new MySQL username.
– password
● The new MySQL password.
– database
● The MySQL database. If not specified, the current selected database is
used.
– link_identifier
● The MySQL connection. If the link identifier is not specified, the last link
opened by mysql_connect() is assumed. If no such link is found, it will try to
create one as if mysql_connect() was called with no arguments. If by chance
no connection is found or established, an E_WARNING level warning is
generated.
● Return Values
– Returns TRUE on success or FALSE on failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_client_encoding
● mysql_client_encoding — Returns the name of the character set
● string mysql_client_encoding ( [resource $link_identifier] )
● Retrieves the character_set variable from MySQL.
● Parameters
– link_identifier
● The MySQL connection. If the link identifier is not specified,
the last link opened by mysql_connect() is assumed. If no such
link is found, it will try to create one as if mysql_connect() was
called with no arguments. If by chance no connection is found or
established, an E_WARNING level warning is generated.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_client_encoding
<?php
$link = mysql_connect('localhost',
'mysql_user', 'mysql_password');
$charset = mysql_client_encoding($link);

echo "The current character set is:


$charset\n";
?>

The above example will output something


similar to:

The current character set is: latin1

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_close
● mysql_close — Close MySQL connection
● Description
● bool mysql_close ( [resource $link_identifier] )
● mysql_close() closes the non-persistent connection to the MySQL server that's associated
with the specified link identifier. If link_identifier isn't specified, the last opened link is used.
● Using mysql_close() isn't usually necessary, as non-persistent open links are automatically
closed at the end of the script's execution. See also freeing resources.
● Parameters
– link_identifier
● The MySQL connection. If the link identifier is not specified, the last link
opened by mysql_connect() is assumed. If no such link is found, it will try to
create one as if mysql_connect() was called with no arguments. If by chance no
connection is found or established, an E_WARNING level warning is generated.
● Return Values
● Returns TRUE on success or FALSE on failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_close
<?php
$link = mysql_connect('localhost',
'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' .
mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>

The above example will output:

Connected successfully

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_connect
● mysql_connect — Open a connection to a MySQL Server
● resource mysql_connect ( [string $server [, string $username [, string
$password [, bool $new_link [, int $client_flags]]]]] )
● Opens or reuses a connection to a MySQL server.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_connect
● Parameters
– server
● The MySQL server. It can also include a port number. e.g.
"hostname:port" or a path to a local socket e.g. ":/path/to/socket"
for the localhost.
● If the PHP directive mysql.default_host is undefined (default),
then the default value is 'localhost:3306'. In SQL safe mode, this
parameter is ignored and value 'localhost:3306' is always used.
– username
● The username. Default value is defined by mysql.default_user.
In SQL safe mode, this parameter is ignored and the name of the
user that owns the server process is used.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_connect
● password
● The password. Default value is defined by
mysql.default_password. In SQL safe mode, this parameter is
ignored and empty password is used.
– new_link
● If a second call is made to mysql_connect() with the same
arguments, no new link will be established, but instead, the link
identifier of the already opened link will be returned. The
new_link parameter modifies this behavior and makes
mysql_connect() always open a new link, even if
mysql_connect() was called before with the same parameters. In
SQL safe mode, this parameter is ignored.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_connect
● client_flags
● The client_flags parameter can be a combination of the
following constants: MYSQL_CLIENT_SSL,
MYSQL_CLIENT_COMPRESS,
MYSQL_CLIENT_IGNORE_SPACE or
MYSQL_CLIENT_INTERACTIVE. Read the section about Table
173, “MySQL client constants” for further information. In SQL
safe mode, this parameter is ignored.
– Return Values
● Returns a MySQL link identifier on success, or FALSE on failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_connect
<?php
// we connect to example.com and port 3307
$link = mysql_connect('example.com:3307', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
// we connect to localhost at port 3307
$link = mysql_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}echo 'Connected successfully';
mysql_close($link);
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_connect
● Parameters
– database_name
● The name of the database being created.
– link_identifier
● The MySQL connection. If the link identifier is not specified,
the last link opened by mysql_connect() is assumed. If no such
link is found, it will try to create one as if mysql_connect() was
called with no arguments. If by chance no connection is found or
established, an E_WARNING level warning is generated.
● Return Values
– Returns TRUE on success or FALSE on failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_create_db
● Create a MySQL database
● bool mysql_create_db ( string $database_name [, resource
$link_identifier] )
● mysql_create_db() attempts to create a new database on the server
associated with the specified link identifier.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

<?php
mysql_create_db
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$sql = 'CREATE DATABASE my_db';
if (mysql_query($sql, $link)) {
echo "Database my_db created successfully\n";
} else {
echo 'Error creating database: ' . mysql_error() . "\n";
}
?>
The above example will output something similar to:
Database my_db created successfully

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_data_seek
● Move internal result pointer
● bool mysql_data_seek ( resource $result, int $row_number )
● mysql_data_seek() moves the internal row pointer of the MySQL result
associated with the specified result identifier to point to the specified row
number. The next call to a MySQL fetch function, such as
mysql_fetch_assoc(), would return that row.
● row_number starts at 0. The row_number should be a value in the range
from 0 to mysql_num_rows() - 1. However if the result set is empty
(mysql_num_rows() == 0), a seek to 0 will fail with a E_WARNING and
mysql_data_seek() will return FALSE.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_data_seek
● Parameters
– result
● The result resource that is being evaluated. This result comes
from a call to mysql_query().
– row_number
● The desired row number of the new result pointer.
● Return Values
– Returns TRUE on success or FALSE on failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_db_name
● Get result data
● Description
● string mysql_db_name ( resource $result, int $row [, mixed $field] )

● Retrieve the database name from a call to mysql_list_dbs().

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_db_name
● Parameters
– result
● The result pointer from a call to mysql_list_dbs().
– row
● The index into the result set.
– field
● The field name.
– Return Values
● Returns the database name on success, and FALSE on failure.

If FALSE is returned, use mysql_error() to determine the nature


of the error.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_db_name
<?php
error_reporting(E_ALL);

$link = mysql_connect('dbhost', 'username', 'password');


$db_list = mysql_list_dbs($link);

$i = 0;
$cnt = mysql_num_rows($db_list);
while ($i < $cnt) {
echo mysql_db_name($db_list, $i) . "\n";
$i++;
}
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_db_query
● Send a MySQL query
● resource mysql_db_query ( string $database, string $query [, resource $link_identifier] )
● mysql_db_query() selects a database, and executes a query on it.
● Parameters
– database
● The name of the database that will be selected.
– query
● The MySQL query.
– link_identifier

● The MySQL connection. If the link identifier is not specified, the last link
opened by mysql_connect() is assumed. If no such link is found, it will try to
create one as if mysql_connect() was called with no arguments. If by chance no
connection is found or established, an E_WARNING level warning is generated.
● Return Values
● Returns a positive MySQL result resource to the query result, or FALSE on error.
The function also returns TRUE/FALSE for INSERT/UPDATE/DELETE queries to
indicate success/failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_db_query
$sql = 'SELECT foo FROM bar WHERE id = 42';
<?php
$result = mysql_query($sql, $link);
if (!$result) {
if (!$link = mysql_connect('mysql_host',
'mysql_user', 'mysql_password')) { echo "DB Error, could not query the database\n";
echo 'Could not connect to mysql'; echo 'MySQL Error: ' . mysql_error();
exit; exit;
} }
while ($row = mysql_fetch_assoc($result)) {
if (!mysql_select_db('mysql_dbname', $link)) { echo $row['foo'];
echo 'Could not select database'; }
exit; mysql_free_result($result);
} ?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_drop_db
● Drop (delete) a MySQL database
● bool mysql_drop_db ( string $database_name [, resource
$link_identifier] )
● mysql_drop_db() attempts to drop (remove) an entire database from the
server associated with the specified link identifier. This function is
deprecated, it is preferable to use mysql_query() to issue a sql DROP
DATABASE statement instead.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_drop_db
● Parameters
– database_name
● The name of the database that will be deleted.
– link_identifier
● The MySQL connection. If the link identifier is not specified, the
last link opened by mysql_connect() is assumed. If no such link is
found, it will try to create one as if mysql_connect() was called with
no arguments. If by chance no connection is found or established,
an E_WARNING level warning is generated.
– Return Values
● Returns TRUE on success or FALSE on failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_drop_db
mysql_drop_db() alternative example
<?php
$link = mysql_connect('localhost', 'mysql_user',
'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$sql = 'DROP DATABASE my_db';
if (mysql_query($sql, $link)) {
echo "Database my_db was successfully dropped\n";
} else {
echo 'Error dropping database: ' . mysql_error() . "\n";
}
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_errno
● Returns the numerical value of the error message from previous MySQL
operation
● int mysql_errno ( [resource $link_identifier] )
● Returns the error number from the last MySQL function.
● Errors coming back from the MySQL database backend no longer issue
warnings. Instead, use mysql_errno() to retrieve the error code. Note that
this function only returns the error code from the most recently executed
MySQL function (not including mysql_error() and mysql_errno()), so if you
want to use it, make sure you check the value before calling another MySQL
function.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_errno
<?php
$link = mysql_connect("localhost", "mysql_user",
"mysql_password");
if (!mysql_select_db("nonexistentdb", $link)) {
echo mysql_errno($link) . ": " . mysql_error($link). "\n";
}
mysql_select_db("kossu", $link);
if (!mysql_query("SELECT * FROM nonexistenttable", $link)) {
echo mysql_errno($link) . ": " . mysql_error($link) . "\n";
}
?>

The above example will output something similar to:


1049: Unknown database 'nonexistentdb'
1146: Table 'kossu.nonexistenttable' doesn't exist

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_error
● Returns the text of the error message from previous MySQL operation
● string mysql_error ( [resource $link_identifier] )
● Returns the error text from the last MySQL function. Errors coming back
from the MySQL database backend no longer issue warnings. Instead,
use mysql_error() to retrieve the error text. Note that this function only
returns the error text from the most recently executed MySQL function
(not including mysql_error() and mysql_errno()), so if you want to use it,
make sure you check the value before calling another MySQL function.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_error
● Parameters
● link_identifier
– The MySQL connection. If the link identifier is not specified, the last
link opened by mysql_connect() is assumed. If no such link is found,
it will try to create one as if mysql_connect() was called with no
arguments. If by chance no connection is found or established, an
E_WARNING level warning is generated.
● Return Values
– Returns the error text from the last MySQL function, or '' (empty
string) if no error occurred.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_error
<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");

mysql_select_db("nonexistentdb", $link);
echo mysql_errno($link) . ": " . mysql_error($link). "\n";

mysql_select_db("kossu", $link);
mysql_query("SELECT * FROM nonexistenttable", $link);
echo mysql_errno($link) . ": " . mysql_error($link) . "\n";
?>
The above example will output something similar to:
1049: Unknown database 'nonexistentdb'
1146: Table 'kossu.nonexistenttable' doesn't exist

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_escape_string
● Escapes a string for use in a mysql_query
● string mysql_escape_string ( string $unescaped_string )
● This function will escape the unescaped_string, so that it is
safe to place it in a mysql_query(). This function is
deprecated.
● This function is identical to mysql_real_escape_string()
except that mysql_real_escape_string() takes a connection
handler and escapes the string according to the current
character set. mysql_escape_string() does not take a
connection argument and does not respect the current
charset setting.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_escape_string
● Parameters
– unescaped_string
● The string that is to be escaped.
● Return Values
– Returns the escaped string.
<?php
$item = "Zak's Laptop";
$escaped_item = mysql_escape_string($item);
printf("Escaped string: %s\n", $escaped_item);
?>
The above example will output:
Escaped string: Zak\'s Laptop

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_fetch_array
● Fetch a result row as an associative array, a numeric array, or both
● array mysql_fetch_array ( resource $result [, int $result_type] )
● Returns an array that corresponds to the fetched row and moves the internal
data pointer ahead.
● Parameters
● result
● The result resource that is being evaluated. This result comes from a call
to mysql_query().
● result_type
● The type of array that is to be fetched. It's a constant and can take the
following values: MYSQL_ASSOC, MYSQL_NUM, and the default value of
MYSQL_BOTH.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_fetch_array
● Return Values
● Returns an array that corresponds to the fetched row, or FALSE if there
are no more rows. The type of returned array depends on how
result_type is defined. By using MYSQL_BOTH (default), you'll get an
array with both associative and number indices. Using MYSQL_ASSOC,
you only get associative indices (as mysql_fetch_assoc() works), using
MYSQL_NUM, you only get number indices (as mysql_fetch_row()
works).
● If two or more columns of the result have the same field names, the last
column will take precedence. To access the other column(s) of the same
name, you must use the numeric index of the column or make an alias
for the column. For aliased columns, you cannot access the contents
with the original column name.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_fetch_array
<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
$result = mysql_query("SELECT id, name FROM mytable");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
printf("ID: %s Name: %s", $row[0], $row[1]);
}
mysql_free_result($result);
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_fetch_assoc
● Fetch a result row as an associative array
● array mysql_fetch_assoc ( resource $result )
● Returns an associative array that corresponds to the fetched
row and moves the internal data pointer ahead.
mysql_fetch_assoc() is equivalent to calling
mysql_fetch_array() with MYSQL_ASSOC for the optional
second parameter. It only returns an associative array.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_fetch_assoc
● Parameters
– result
● The result resource that is being evaluated. This result
comes from a call to mysql_query().
– Return Values
● Returns an associative array that corresponds to the

fetched row, or FALSE if there are no more rows.


● If two or more columns of the result have the same field

names, the last column will take precedence. To access the


other column(s) of the same name, you either need to
access the result with numeric indices by using
mysql_fetch_row() or add alias names. See the example at
the mysql_fetch_array() description about aliases.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

<?php
array_fetch_assoc$sql = "SELECT id as userid, fullname, userstatus
$conn = mysql_connect("localhost",
"mysql_user", "mysql_password"); FROM sometable

if (!$conn) { WHERE userstatus = 1";

echo "Unable to connect to DB: " . $result = mysql_query($sql);


mysql_error(); if (!$result) {
exit; echo "Could not successfully run query ($sql) from DB: " .
} mysql_error();

if (!mysql_select_db("mydbname")) { exit;

echo "Unable to select mydbname: " . }


mysql_error(); if (mysql_num_rows($result) == 0) {
exit; echo "No rows found, nothing to print so am exiting";
} exit;
}

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_fetch_field
● Get column information from a result and return as an object
● object mysql_fetch_field ( resource $result [, int $field_offset] )
● Returns an object containing field information. This function
can be used to obtain information about fields in the provided
query result.
● Parameters
– result
● The result resource that is being evaluated. This
result comes from a call to mysql_query().
– field_offset
● The numerical field offset. If the field offset is not
specified, the next field that was not yet retrieved by this
function is retrieved. The field_offset starts at 0.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_fetch_fields
● Return Values
● Returns an object containing field information. The properties
of the object are:

* name - column name
* table - name of the table the column belongs to
* def - default value of the column
* max_length - maximum length of the column
* not_null - 1 if the column cannot be NULL
* primary_key - 1 if the column is a primary key
* unique_key - 1 if the column is a unique key
* multiple_key - 1 if the column is a non-unique key
* numeric - 1 if the column is numeric
* blob - 1 if the column is a BLOB
* type - the type of the column
* unsigned - 1 if the column is unsigned
* zerofill - 1 if the column is zero-filled

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_fetch_fields
$i = 0; not_null: $meta->not_null
while ($i < mysql_num_fields($result)) { numeric: $meta->numeric
echo "Information for column $i:<br />\n"; primary_key: $meta->primary_key
$meta = mysql_fetch_field($result, $i);
echo "<pre> table: $meta->table
if (!$meta) {
blob: $meta->blob type: $meta->type
echo "No information available<br />\n";
max_length: $meta->max_length default: $meta->def
}
multiple_key: $meta->multiple_key unique_key: $meta->unique_key
name: $meta->name unsigned: $meta->unsigned
zerofill: $meta->zerofill
</pre>";
$i++;
}

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_fetch_length
● Get the length of each output in a result
● array mysql_fetch_lengths ( resource $result )
● Returns an array that corresponds to the lengths of each field
in the last row fetched by MySQL.
● mysql_fetch_lengths() stores the lengths of each result
column in the last row returned by mysql_fetch_row(),
mysql_fetch_assoc(), mysql_fetch_array(), and
mysql_fetch_object() in an array, starting at offset 0.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0
<?php
mysql_fetch_length
$result = mysql_query("SELECT id,email
FROM people WHERE id = '42'");
if (!$result) {
● Parameters echo 'Could not run query: ' . mysql_error();
– result Array
exit;
● The result (
resource that is } [id] => 42
[email] =>
being evaluated. $row = mysql_fetch_assoc($result); user@example.com
This result )
$lengths = mysql_fetch_lengths($result);
comes from a Array
call to (
[0] => 2
mysql_query(). print_r($row); [1] => 16
● Return Values )
print_r($lengths);
– An array of lengths
on success, or ?>
FALSE on failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_fetch_object
● Fetch a result row as an object
● object mysql_fetch_object ( resource $result [, string
$class_name [, array $params]] )
● Returns an object with properties that correspond to the
fetched row and moves the internal data pointer ahead.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_fetch_object
● Parameters
– Result
● The result resource that is being evaluated. This result

comes from a call to mysql_query().


– class_name
● The name of the class to instantiate, set the properties

of and return. If not specified, a stdClass object is


returned.
– Params
● An optional array of parameters to pass to the

constructor for class_name objects.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_fetch_object
● Return Values
– Returns an object with properties that correspond to the
fetched row, or FALSE if there are no more rows.
– mysql_fetch_row() fetches one row of data from the result
associated with the specified result identifier. The row is
returned as an array. Each result column is stored in an
array offset, starting at offset 0.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_fetch_object
<?php
<?php
mysql_connect("hostname", "user",
"password");
$row = mysql_fetch_object($result);
mysql_select_db("mydb");
$result = mysql_query("select * from
mytable"); /* this is valid */
while ($row = echo $row->field;
mysql_fetch_object($result)) {
/* this is invalid */
echo $row->user_id;
// echo $row->0;
echo $row->fullname;
}
?>
mysql_free_result($result);
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_fetch_row
● Get a result row as an enumerated array
● array mysql_fetch_row ( resource $result )
● Returns a numerical array that corresponds to the fetched
row and moves the internal data pointer ahead.
● Parameters
● result
● The result resource that is being evaluated. This result
comes from a call to mysql_query().

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_fetch_row
● Return Values
● Returns an numerical array that corresponds to the fetched
row, or FALSE if there are no more rows.
● mysql_fetch_row() fetches one row of data from the result
associated with the specified result identifier. The row is
returned as an array. Each result column is stored in an array
offset, starting at offset 0.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_fetch_row
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);

echo $row[0]; // 42
echo $row[1]; // the email value
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_field_flags
● Get the flags associated with the specified field in a result
● string mysql_field_flags ( resource $result, int $field_offset )
● mysql_field_flags() returns the field flags of the specified field.
The flags are reported as a single word per flag separated by
a single space, so that you can split the returned value using
explode().

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_field_flags
● Parameters
– Result
● The result resource that is being evaluated. This result

comes from a call to mysql_query().


– field_offset
● The numerical field offset. The field_offset starts at 0.
If field_offset does not exist, an error of level
E_WARNING is also issued.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_field_flags
● Return Values
– Returns a string of flags associated with the result, or
FALSE on failure.
– The following flags are reported, if your version of MySQL
is current enough to support them: "not_null",
"primary_key", "unique_key", "multiple_key", "blob",
"unsigned", "zerofill", "binary", "enum", "auto_increment"
and "timestamp".

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

<?php mysql_field_flags
$result = mysql_query("SELECT id,email
FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error(); not_null primary_key
exit; auto_increment
Array
} (
[0] => not_null
$flags = mysql_field_flags($result, 0); [1] => primary_key
[2] =>
auto_increment
echo $flags; )
print_r(explode(' ', $flags));
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_field_len
● Returns the length of the specified field
● int mysql_field_len ( resource $result, int $field_offset )
● mysql_field_len() returns the length of the specified field.
● Parameters
– result
● The result resource that is being evaluated. This result
comes from a call to mysql_query().
– field_offset
● The numerical field offset. The field_offset starts at 0. If
field_offset does not exist, an error of level E_WARNING is
also issued.
● Return Values
– The length of the specified field index on success, or FALSE on
failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_field_len
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}

// Will get the length of the id field as specified in the database


// schema.
$length = mysql_field_len($result, 0);
echo $length;
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_field_len
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id =
'42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}

// Will get the length of the id field as specified in the database


// schema.
$length = mysql_field_len($result, 0);
echo $length;
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_field_name
● Get the name of the specified field in a result
● string mysql_field_name ( resource $result, int $field_offset )
● mysql_field_name() returns the name of the specified field index.
● Parameters
– result
● The result resource that is being evaluated. This result
comes from a call to mysql_query().
– field_offset
● The numerical field offset. The field_offset starts at 0. If
field_offset does not exist, an error of level E_WARNING is
also issued.
● Return Values
– The name of the specified field index on success, or FALSE on
failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_field_name
<?php $dbname = 'mydb';
/* The users table consists of three fields: $db_selected = mysql_select_db($dbname, $link);
* user_id if (!$db_selected) {
* username die("Could not set $dbname: " . mysql_error());
* password. }
*/ $res = mysql_query('select * from users', $link);
$link = @mysql_connect('localhost', echo mysql_field_name($res, 0) . "\n";
'mysql_user', 'mysql_password');
echo mysql_field_name($res, 2);
if (!$link) {
?>
die('Could not connect to MySQL server: ' .
mysql_error()); The above example will output:
} user_id
password

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_field_seek
● Set result pointer to a specified field offset
● bool mysql_field_seek ( resource $result, int $field_offset
)
● Seeks to the specified field offset. If the next call to
mysql_fetch_field() doesn't include a field offset, the field
offset specified in mysql_field_seek() will be returned.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_field_seek
● Parameters
– result
● The result resource that is being evaluated. This

result comes from a call to mysql_query().


– field_offset
● The numerical field offset. The field_offset starts
at 0. If field_offset does not exist, an error of level
E_WARNING is also issued.
● Return Values
– Returns TRUE on success or FALSE on failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_field_table
● Get name of the table the specified field is in
● string mysql_field_table ( resource $result, int
$field_offset )
● Returns the name of the table that the specified field is
in.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_field_table
● Parameters
– result
● The result resource that is being evaluated. This

result comes from a call to mysql_query().


– field_offset
● The numerical field offset. The field_offset starts at

0. If field_offset does not exist, an error of level


E_WARNING is also issued.
● Return Values
– The name of the table on success.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_field_table
<?php
$result = mysql_query("SELECT
name,comment FROM people,comments");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}

// Assuming name is in the people table


$table = mysql_field_table($result, 'name');
echo $table; // people
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_field_type
● Get the type of the specified field in a result
● string mysql_field_type ( resource $result, int $field_offset )
● mysql_field_type() is similar to the mysql_field_name()
function. The arguments are identical, but the field type is
returned instead.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_field_type
● Parameters
– result
● The result resource that is being evaluated. This result

comes from a call to mysql_query().


– field_offset
● The numerical field offset. The field_offset starts at 0. If

field_offset does not exist, an error of level


E_WARNING is also issued.
● Return Values
– The returned field type will be one of "int", "real", "string",
"blob", and others as detailed in the » MySQL
documentation.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

<?php mysql_field_type
mysql_connect("localhost", "mysql_username",
"mysql_password");
mysql_select_db("mysql"); echo "The table has the following fields:\n";

$result = mysql_query("SELECT * FROM func"); for ($i=0; $i < $fields; $i++) {


$fields = mysql_num_fields($result); $type = mysql_field_type($result, $i);

$rows = mysql_num_rows($result); $name = mysql_field_name($result, $i);

$table = mysql_field_table($result, 0); $len = mysql_field_len($result, $i);

echo "Your '" . $table . "' table has " . $fields . " $flags = mysql_field_flags($result, $i);
fields and " . $rows . " record(s)\n"; echo $type . " " . $name . " " . $len . " " . $flags . "\n";
}
mysql_free_result($result);
mysql_close();
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_field_type

Your 'func' table has 4 fields and 1 record(s)


The table has the following fields:
string name 64 not_null primary_key binary
int ret 1 not_null
string dl 128 not_null
string type 9 not_null enum

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_free_result
● Free result memory
● bool mysql_free_result ( resource $result )
● mysql_free_result() will free all memory associated with the result
identifier result.
● mysql_free_result() only needs to be called if you are concerned
about how much memory is being used for queries that return large
result sets. All associated result memory is automatically freed at the
end of the script's execution.
● Parameters
– result
● The result resource that is being evaluated. This result comes

from a call to mysql_query().


● Return Values
– Returns TRUE on success or FALSE on failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_free_result
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
/* Use the result, assuming we're done with it afterwords */
$row = mysql_fetch_assoc($result);
/* Now we free up the result and continue on with our script */
mysql_free_result($result);
echo $row['id'];
echo $row['email'];
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_client_info
● Get MySQL client info
● string mysql_get_client_info ( void )
● mysql_get_client_info() returns a string that represents
the client library version.
● Return Values
● The MySQL client version. <?php
printf("MySQL client info: %s\n",
mysql_get_client_info());
?>
The above example will output something similar
to:
MySQL client info: 3.23.39

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_host_info
● Get MySQL host info
● string mysql_get_host_info ( [resource $link_identifier] )
● Describes the type of connection in use for the connection,
including the server host name.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_host_info
● Parameters
– link_identifier
● The MySQL connection. If the link identifier is not

specified, the last link opened by mysql_connect() is


assumed. If no such link is found, it will try to create
one as if mysql_connect() was called with no
arguments. If by chance no connection is found or
established, an E_WARNING level warning is
generated.
● Return Values
– Returns a string describing the type of MySQL connection
in use for the connection or FALSE on failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_host_info
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
printf("MySQL host info: %s\n", mysql_get_host_info());
?>
The above example will output something similar to:
MySQL host info: Localhost via UNIX socket

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_get_proto_info
● Get MySQL protocol info
● int mysql_get_proto_info ( [resource $link_identifier] )
● Retrieves the MySQL protocol.
● Parameters
– link_identifier
● The MySQL connection. If the link identifier is not

specified, the last link opened by mysql_connect() is


assumed. If no such link is found, it will try to create
one as if mysql_connect() was called with no
arguments. If by chance no connection is found or
established, an E_WARNING level warning is
generated.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_get_proto_info
● Return Values
– Returns the MySQL protocol on success, or FALSE on
failure.
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
printf("MySQL protocol version: %s\n", mysql_get_proto_info());
?>
The above example will output something similar to:
MySQL protocol version: 10

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_get_server_info
● Get MySQL server info
● string mysql_get_server_info ( [resource $link_identifier] )
● Retrieves the MySQL server version.
● Parameters
– link_identifier
● The MySQL connection. If the link identifier is not

specified, the last link opened by mysql_connect() is


assumed. If no such link is found, it will try to create
one as if mysql_connect() was called with no
arguments. If by chance no connection is found or
established, an E_WARNING level warning is
generated.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_get_server_info
● Return Values
– Returns the MySQL server version on success, or FALSE
on failure.
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
printf("MySQL server version: %s\n", mysql_get_server_info());
?>
The above example will output something similar to:
MySQL server version: 4.0.1-alpha

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_info
● Get information about the most recent query
● string mysql_info ( [resource $link_identifier] )
● Returns detailed information about the last query.
● Parameters
– link_identifier
● The MySQL connection. If the link identifier is not

specified, the last link opened by mysql_connect() is


assumed. If no such link is found, it will try to create
one as if mysql_connect() was called with no
arguments. If by chance no connection is found or
established, an E_WARNING level warning is
generated.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_info
● Return Values
– Returns information about the statement on success, or
FALSE on failure. See the example below for which
statements provide information, and what the returned
value may look like. Statements that are not listed will
return FALSE.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_insert_id
● Get the ID generated from the previous INSERT operation
● int mysql_insert_id ( [resource $link_identifier] )
● Retrieves the ID generated for an AUTO_INCREMENT column by
the previous INSERT query.
● Parameters
– link_identifier
● The MySQL connection. If the link identifier is not specified,

the last link opened by mysql_connect() is assumed. If no


such link is found, it will try to create one as if
mysql_connect() was called with no arguments. If by chance
no connection is found or established, an E_WARNING
level warning is generated.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_insert_id
● Return Values
● The ID generated for an AUTO_INCREMENT column by the
previous INSERT query on success, 0 if the previous query does
not generate an AUTO_INCREMENT value, or FALSE if no
MySQL connection was established.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_insert_id
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('intelli')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_list_dbs
● List databases available on a MySQL server
● resource mysql_list_dbs ( [resource
$link_identifier] )
● Returns a result pointer containing the
databases available from the current mysql
daemon.
● function to traverse this result pointer, or any
function for result tables, such as
mysql_fetch_array().

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_list_dbs
● Parameters
– link_identifier
● The MySQL connection. If the link identifier is not
specified, the last link opened by mysql_connect() is
assumed. If no such link is found, it will try to create
one as if mysql_connect() was called with no
arguments. If by chance no connection is found or
established, an E_WARNING level warning is
generated.
● Return Values
– Returns a result pointer resource on success, or
FALSE on failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_list_dbs
<?php
$link = mysql_connect('localhost', 'mysql_user',
'mysql_password');
$db_list = mysql_list_dbs($link);

while ($row = mysql_fetch_object($db_list)) {


echo $row->Database . "\n";
}
?>
The above example will output something similar to:
database1
database2
database3

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_list_fields
● List MySQL table fields
● resource mysql_list_fields ( string $database_name, string
$table_name [, resource $link_identifier] )
● Retrieves information about the given table name.
● This function is deprecated. It is preferable to use
mysql_query() to issue a SQL SHOW COLUMNS FROM
table [LIKE 'name'] statement instead.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_list_fields
● Parameters
– database_name
● The name of the database that's being queried.

– table_name
● The name of the table that's being queried.

– link_identifier
– The MySQL connection. If the link identifier is not specified, the
last link opened by mysql_connect() is assumed. If no such link is
found, it will try to create one as if mysql_connect() was called
with no arguments. If by chance no connection is found or
established, an E_WARNING level warning is generated.
● Return Values
● A result pointer resource on success, or FALSE on failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_list_fields
Alternate to deprecated mysql_list_fields()
<?php This example will output something
$result = mysql_query("SHOW COLUMNS FROM sometable"); similar to:
Array
if (!$result) { (
echo 'Could not run query: ' . mysql_error(); [Field] => id
[Type] => int(7)
exit; [Null] =>
[Key] => PRI
}
[Default] =>
if (mysql_num_rows($result) > 0) { [Extra] => auto_increment
)
while ($row = mysql_fetch_assoc($result)) { Array
print_r($row); (
[Field] => email
} [Type] => varchar(100)
[Null] =>
} [Key] =>
?> [Default] =>
[Extra] =>
)

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_list_process
● List MySQL processes
● resource mysql_list_processes ( [resource $link_identifier] )
● Retrieves the current MySQL server threads.
● Parameters
– link_identifier
● The MySQL connection. If the link identifier is not

specified, the last link opened by mysql_connect() is


assumed. If no such link is found, it will try to create
one as if mysql_connect() was called with no
arguments. If by chance no connection is found or
established, an E_WARNING level warning is
generated.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_list_processes
● Return Values
– A result pointer resource on success, or FALSE on failure.

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$result = mysql_list_processes($link);
while ($row = mysql_fetch_assoc($result)){
printf("%s %s %s %s %s\n", $row["Id"], $row["Host"], $row["db"],
$row["Command"], $row["Time"]);
}
mysql_free_result($result); The above example will output something similar
to:
?>
1 localhost test Processlist 0
4 localhost mysql sleep 5

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_list_tables
● List tables in a MySQL database
● resource mysql_list_tables ( string $database [, resource
$link_identifier] )
● Retrieves a list of table names from a MySQL database.
● This function is deprecated. It is preferable to use
mysql_query() to issue a SQL SHOW TABLES [FROM
db_name] [LIKE 'pattern'] statement instead.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

msql_list_tables
● Parameters
– database
● The name of the database

– link_identifier
● The MySQL connection. If the link identifier is not

specified, the last link opened by mysql_connect() is


assumed. If no such link is found, it will try to create one
as if mysql_connect() was called with no arguments. If
by chance no connection is found or established, an
E_WARNING level warning is generated.
● Return Values
– A result pointer resource on success, or FALSE on failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_list_tables
mysql_list_tables() alternative example if (!$result) {
<?php echo "DB Error, could not list tables\n";
$dbname = 'mysql_dbname'; echo 'MySQL Error: ' . mysql_error();
if (!mysql_connect('mysql_host', 'mysql_user', exit;
'mysql_password')) {
}
echo 'Could not connect to mysql';
while ($row = mysql_fetch_row($result)) {
exit;
echo "Table: {$row[0]}\n";
}
}
$sql = "SHOW TABLES FROM $dbname";
mysql_free_result($result);
$result = mysql_query($sql);
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_num_fields
● Get number of fields in result
● int mysql_num_fields ( resource $result )
● Retrieves the number of fields from a query.
● Parameters
● result
● The result resource that is being evaluated. This result
comes from a call to mysql_query().
● Return Values
● Returns the number of fields in the result set resource on
success, or FALSE on failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_num_fields
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}

/* returns 2 because id,email === two fields */


echo mysql_num_fields($result);
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_num_rows
● Get number of rows in result
● int mysql_num_rows ( resource $result )
● Retrieves the number of rows from a result set. This
command is only valid for statements like SELECT or SHOW
that return an actual result set. To retrieve the number of rows
affected by a INSERT, UPDATE, REPLACE or DELETE
query, use mysql_affected_rows().

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_num_rows
● Parameters
– result
● The result resource that is being evaluated. This result

comes from a call to mysql_query().


● Return Values
– The number of rows in a result set on success, or FALSE
on failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_num_rows
<?php

$link = mysql_connect("localhost", "mysql_user", "mysql_password");


mysql_select_db("database", $link);

$result = mysql_query("SELECT * FROM table1", $link);


$num_rows = mysql_num_rows($result);

echo "$num_rows Rows\n";

?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_pconnect
● Open a persistent connection to a MySQL server
● resource mysql_pconnect ( [string $server [, string
$username [, string $password [, int $client_flags]]]] )
● Establishes a persistent connection to a MySQL server.
● mysql_pconnect() acts very much like mysql_connect() with
two major differences.
● First, when connecting, the function would first try to find a (persistent) link
that's already open with the same host, username and password. If one is
found, an identifier for it will be returned instead of opening a new
connection.
● Second, the connection to the SQL server will not be closed when the
execution of the script ends. Instead, the link will remain open for future use
(mysql_close() will not close links established by mysql_pconnect()).
● This type of link is therefore called 'persistent'.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_pconnect
● Parameters
– server
● The MySQL server. It can also include a port number.

e.g. "hostname:port" or a path to a local socket e.g.


":/path/to/socket" for the localhost.
● If the PHP directive mysql.default_host is undefined

(default), then the default value is 'localhost:3306'


– username
● The username. Default value is the name of the user

that owns the server process.


– password
● The password. Default value is an empty password.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_pconnect
● client_flags
● The client_flags parameter can be a combination of the

following constants: MYSQL_CLIENT_SSL,


MYSQL_CLIENT_COMPRESS,
MYSQL_CLIENT_IGNORE_SPACE or
MYSQL_CLIENT_INTERACTIVE.
● Return Values
– Returns a MySQL persistent link identifier on success, or
FALSE on failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_ping
● Ping a server connection or reconnect if there is no
connection
● bool mysql_ping ( [resource $link_identifier] )
● Checks whether or not the connection to the server is
working. If it has gone down, an automatic reconnection
is attempted. This function can be used by scripts that
remain idle for a long while, to check whether or not the
server has closed the connection and reconnect if
necessary.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_ping
● Parameters
– link_identifier
● The MySQL connection. If the link identifier is not specified,

the last link opened by mysql_connect() is assumed. If no


such link is found, it will try to create one as if
mysql_connect() was called with no arguments. If by chance
no connection is found or established, an E_WARNING
level warning is generated.
● Return Values
● Returns TRUE if the connection to the server MySQL server is
working, otherwise FALSE.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_ping
/* Make sure the connection is still alive, if not, try to
<?php reconnect */

set_time_limit(0); if (!mysql_ping($conn)) {

$conn = mysql_connect('localhost', echo 'Lost connection, exiting after query #1';


'mysqluser', 'mypass'); exit;
$db = mysql_select_db('mydb'); }
/* Assuming this query will take a long mysql_free_result($result);
time */
/* So the connection is still alive, let's run another query */
$result = mysql_query($sql);
$result2 = mysql_query($sql2);
if (!$result) {
?>
echo 'Query #1 failed, exiting.';
exit;
}

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_real_escape_string
● Escapes special characters in a string for use in a SQL
statement
● string mysql_real_escape_string ( string $unescaped_string [,
resource $link_identifier] )
● Escapes special characters in the unescaped_string, taking
into account the current character set of the connection so
that it is safe to place it in a mysql_query(). If binary data is to
be inserted, this function must be used.
● mysql_real_escape_string() calls MySQL's library function
mysql_real_escape_string, which prepends backslashes to
the following characters: \x00, \n, \r, \, ', " and \x1a.
● This function must always (with few exceptions) be used to
make data safe before sending a query to MySQL.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_real_escape_string
● Parameters
– unescaped_string
● The string that is to be escaped.

– link_identifier
– The MySQL connection. If the link identifier is not
specified, the last link opened by mysql_connect() is
assumed. If no such link is found, it will try to create one
as if mysql_connect() was called with no arguments. If by
chance no connection is found or established, an
E_WARNING level warning is generated.
● Return Values
– Returns the escaped string, or FALSE on error.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_real_escape_string

<?php
// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
OR die(mysql_error());

// Query
$query = sprintf("SELECT * FROM users WHERE user='%s' AND
password='%s'",
mysql_real_escape_string($user),
mysql_real_escape_string($password));
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_stat
● Get current system status
● string mysql_stat ( [resource
$link_identifier] )
● mysql_stat() returns the current server
status.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_stat
● Parameters
– link_identifier
● The MySQL connection. If the link identifier is not

specified, the last link opened by mysql_connect() is


assumed. If no such link is found, it will try to create
one as if mysql_connect() was called with no
arguments. If by chance no connection is found or
established, an E_WARNING level warning is
generated.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_stat <?php
$link = mysql_connect('localhost', 'mysql_user',
'mysql_password');
● Return Values $status = explode(' ', mysql_stat($link));
– Returns a string with the
print_r($status);
status for uptime,
?>
threads, queries, open
tables, flush tables and The above example will output something similar to:
queries per second. For Array
(
a complete list of other [0] => Uptime: 5380
status variables, you [1] => Threads: 2
have to use the SHOW [2] => Questions: 1321299
[3] => Slow queries: 0
STATUS SQL [4] => Opens: 26
command. If [5] => Flush tables: 1
link_identifier is invalid, [6] => Open tables: 17
[7] => Queries per second avg: 245.595
NULL is returned. )

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_tablename
● Get table name of field
● string mysql_tablename ( resource $result, int $i )
● Retrieves the table name from a result.
● This function deprecated. It is preferable to use
mysql_query() to issue a SQL SHOW TABLES [FROM
db_name] [LIKE 'pattern'] statement instead.
● Parameters
– result
● A result pointer resource that's returned from

mysql_list_tables().
– i
● The integer index (row/table number)

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_tablename
● Return Values <?php
– The name of the table on mysql_connect("localhost", "mysql_user",
success, or FALSE on "mysql_password");

failure. $result = mysql_list_tables("mydb");


$num_rows = mysql_num_rows($result);
for ($i = 0; $i < $num_rows; $i++) {
echo "Table: ", mysql_tablename($result, $i),
"\n";
}

mysql_free_result($result);
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_thread_id
● Return the current thread ID
● int mysql_thread_id ( [resource $link_identifier] )
● Retrieves the current thread ID. If the connection is
lost, and a reconnect with mysql_ping() is
executed, the thread ID will change. This means
only retrieve the thread ID when needed.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_thread_id
● Parameters
– link_identifier
● The MySQL connection. If the link identifier is not

specified, the last link opened by mysql_connect() is


assumed. If no such link is found, it will try to create
one as if mysql_connect() was called with no
arguments. If by chance no connection is found or
established, an E_WARNING level warning is
generated.
● Return Values
– The thread ID on success, or FALSE on failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_thread_id
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$thread_id = mysql_thread_id($link);
if ($thread_id){
printf("current thread id is %d\n", $thread_id);
}
?>
The above example will output something similar to:
current thread id is 73

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_unbuffered_query
● Send an SQL query to MySQL, without fetching and buffering the result
rows
● resource mysql_unbuffered_query ( string $query [, resource
$link_identifier] )
● mysql_unbuffered_query() sends a SQL query query to MySQL, without
fetching and buffering the result rows automatically, as mysql_query()
does. On the one hand, this saves a considerable amount of memory
with SQL queries that produce large result sets. On the other hand, you
can start working on the result set immediately after the first row has
been retrieved: you don't have to wait until the complete SQL query has
been performed. When using multiple DB-connects, you have to specify
the optional parameter link_identifier.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

mysql_unbuffered_query
● Parameters
– query
● A SQL query

– link_identifier
● The MySQL connection. If the link identifier is not specified, the

last link opened by mysql_connect() is assumed. If no such link


is found, it will try to create one as if mysql_connect() was called
with no arguments. If by chance no connection is found or
established, an E_WARNING level warning is generated.
● Return Values
– For SELECT, SHOW, DESCRIBE or EXPLAIN statements,
mysql_unbuffered_query() returns a resource on success, or FALSE
on error.
● For other type of SQL statements, UPDATE, DELETE, DROP, etc,
mysql_unbuffered_query() returns TRUE on success or FALSE on error.

www.intellibitz.com training@intellibitz.com
CHAPTER 10

PHP AND PEAR DB

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

PEAR
● PEAR(PHP Extention and Application
Repository)is a collection of useful modules
and libraries for PHP.
● PEAR DB databse program abstraction layer
is an add on to php that simplifies
communication between your PHP program
and database program.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

PHP databse abstraction layer


● Web browser

● Apache/IIS
● PHP engine
● Pear DB
● DB extension
● Mysql ,sqlite

● DB server

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

PEAR
● The DB module is one of the most popular
pear modules and is bundled with recent
versions of PHP.
● To use PEAR DB in a PHP program,first you
have to load the DB module.
● To load DB module use require construct.
● require DB.php //case-sensitive

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

DB.php
● DB.php is the main file of the PEAR DB
package.
● It defines the functions that u use to talk to
your database.
● DB::connect(),DB::isError(),query(),
disconnect(),getMessage(),fetchRow() are
some of the functions defined by DB.php

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

require and include


● The require construct tells the PHP
interpreter to execute all the code in the file
DB.php.
● The require and include are simillar but differ
in how they handle errors.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

require and include


● If you try to require a file that dosen't
exists,require consider that as fatal error and
your php program ends.
● If you try to include a file that doesn,t exists,
include reports a warning allowing your
program to continue running.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

DB:: connect()
● You pass DB::connect() a string as
argument.
● The string pssed to DB::connect () is called a
Data Source Network.(DSN)
● Its genral form is
dbProgram://user:pass@hostname/database
● disconnect() is used to terminate connection
with database.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Error handling in PEAR


● DB::isError () returns true if error occurred in
database operations.
● Instead of calling DB::isError () after every
query to check its succeeded or failed ,you
can use setErrorHandling () to establish
default error handling behavior.
● Pass the constant PEAR_ERROR_DIE to
setErrorHandling() to print error message
and exit if a query fails.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

fetchRow()
● The fetchRow() function all field data in a
record.
● This data can be assigned to an array
variable.
● This fetchRow () function returns false if all
row resulted by the query is fetched.
● So the fetchRow () can be iterated using
while loop.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Understanding PEAR helps the programmer
in database operations.
● Requiring DB.php.
● Establishing ans terminating connections
with databases.
● Error handling
● Retriving data from database using PEAR.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

CHAPTER 11

COOKIES AND SESSIONS

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Cookies and Sessions


● Working with Cookies.
● Activating Sessions.
● Storing and retrieving information.
● Login and User identification.
● Why setcookie() and session_start() want to
be at the top of the page.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Cookies and Sessions


● Cookie identifies a web client to web server
● Cookie has a name and a value.
● Session uses cookie to persist data across
requests.
● PHP session capabilities keeps track of
multiple piece of information under one
cookie.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Working with Cookies


● Use setcookie() function to set a cookie.
● Call setcookie() before the page generates
any output.
● Cookies show up in $_COOKIE only when
the web client sends them with the request.
● Cookies are only sent back with requests for
pages in the same directory.
● Path to setcookie() must match the server .

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Cookies
● Setcookie() can take five arguments. First
argument is the name of the cookie. Second
is the value of the cookie. Third argument
specifies the life time of the cookie. Fourth
and fifth are path and domain.
● The default lifetime of the cookie is the
lifetime of the web client. when you quit
internet explorer or Mozilla Firefox the cookie
is automatically deleted.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Activating Sessions
● Sessions use a cookie called PHPSESSID
● The value of PHPSESSID is a random
alphanumeric string
● Use session_start() at the beginning of your
script to use a Session
● Like setcookie(), session_start() must be
called before any output is sent.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Storing and Using Information


● Session data is stored in the $_SESSION
auto-global array
● The PHP interpreter tracks the contents of
the $_SESSION separately for each session
● Call session_start() or set session.auto_start
to on, to access a user's session data
● Session data is not restricted to string and
numbers, its like any other array

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Configuring Sessions
● Sessions work great with no additional tweak
● Session default timeout is 24 minutes
● Use session.gc_maxlifetime configuration
directive, or call ini_set() function from your
program to configure idle time to keep a
session active
● Use ini_set() before session_start()

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Request Headers
● All of the headers in the response from the
web server to the web client have to be at
the beginning of the response
● Functions like setcookie() and
session_start() add headers to the response
● Output buffering lets you mix print
statements, cookie and session functions

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Understanding why cookies are necessary to
identify a particular web browser to a web
server
● Setting a cookie in a PHP program
● Reading a cookie value in a PHP program
● Modifying cookie parameters such as
expiration time, path, and domain
● Deleting a cookie in a PHP program

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Turning on sessions from PHP program or in
the PHP interpreter configuration
● Storing information in session
● Reading information from a session
● Saving form data in a session
● Configuring session expiration and cleanup
● Displaying, validating, and processing a
validation form

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Using encrypted passwords
● Understanding why setcookie() and
session_start() must be called before
anything is printed
● Cookie can't be an array or more
complicated data structure.

www.intellibitz.com training@intellibitz.com
CHAPTER 12

WORKING WITH DATES AND


TIMES

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Handling Dates And Times


● Displaying the Date or Time.
● Parsing a Date or Time.
● Dates and Times in Forms.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Displaying Date or Time


● Use the date( ) or strftime( ) functions to
display the date and time.
● Both strftime( ) and date( )take two
arguments.
● The first argument controls how the date or
time string is formatted.
● The second argument controls what date or
time is used.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Displaying Date or Time


● In date ( ) function / can't be used for
escaping.
● With strftime ( ) the things in the format string
that get replaced by time and date values are
set off percentage signs.
● The strftime( ) format strings are different
from printf( ) format strings.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Displaying Date and Time


● The date( ) and strftime( )functions have
their strong points.
● Strftime( ) is better because we don't want to
worry about letters with out percentage sign
turning into time or date values.
● Date ( ) is better because it supports leap
year indicator and trims leading zeros from
some values.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Displaying Date and Time


● Date( ) is php specific function. It operates
on any OS.
● The strftime( ) is a php function that relies on
underlying operating system functions.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Parsing Date or Time


● Epoch timestamp: The number of seconds
that have elapsed since midnight on
January 1,1970.
● If you have discrete date or time parts then
use mktime ( )
● The mktime ( ) accepts an hour, minute,
second,month,days and year and returns the
corresponding epoch time stamps.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Parsing Date and Time


● Use strtotime( ),when you want the epoch
timestamp for something relative to a time
you know.
● Strtotime( ) understands English description
of relative times and returns an appropriate
epoch time stamp.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Parsing Date and Time


● Like date() and strftime(),strtotime() also
accept an epoch time stamp second
argument to use as the starting point for its
calculation

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Dates and Time in Form


● When you need a user to input a date in a
form ,the best thing to do is to <select>
menus
● This restricts the possible input to what ever
you display in the menus.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Defining some time and date handling
vocabulary such as epoch timestamp, time
and date parts and formatted date and time
string.
● Printing formatted time and date string with
strftime( ) and date( ).
● Making an epoch timestamp with mktime ( ).

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter summary
● Making an epoch timestamp with strtotime().
● Displaying form elements to allow for date or
time input.

www.intellibitz.com training@intellibitz.com
CHAPTER 13

DATE AND TIME FUNTIONS

www.intellibitz.com training@intellibitz.com
INTELLI BITZ
INTELLIBITZ
Technologies
TD_PHP_V1.0.0
PHP Web Programming
TD_PHP_V1.0.0

checkdate
● Validate a Gregorian date
● bool checkdate ( int $month, int $day, int $year )
● Checks the validity of the date formed by the arguments. A
date is considered valid if each parameter is properly defined.
● Parameters
– month
● The month is between 1 and 12 inclusive.

– day
● The day is within the allowed number of days for the

given month. Leap years are taken into consideration.

www.intellibitz.com training@intellibitz.com
INTELLI BITZ
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

checkdate
– year
● The year is between 1 and 32767 inclusive.

● Return Values
– Returns TRUE if the date given is valid; otherwise returns
FALSE
<?php
var_dump(checkdate(12, 31, 2000));
var_dump(checkdate(2, 29, 2001));
?>
The above example will output:
bool(true)
bool(false)

www.intellibitz.com training@intellibitz.com
INTELLI BITZ
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

date_create
● Returns new DateTime object
● DateTime date_create ( [string $time [,
DateTimeZone $timezone]] )
● DateTime DateTime::__construct ( [string
$time [, DateTimeZone $timezone]] )

www.intellibitz.com training@intellibitz.com
INTELLI BITZ
INTELLIBITZ
Technologies
TD_PHP_V1.0.0
PHP Web Programming
TD_PHP_V1.0.0

date_create
● Parameters
– time
● String in a format accepted by strtotime(), defaults to
"now".
– timezone
● Time zone of the time.
● Return Values
– Returns DateTime object on success or FALSE
on failure.

www.intellibitz.com training@intellibitz.com
INTELLI BITZ
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

date_date_set
● Sets the date
● void date_date_set ( DateTime $object, int
$year, int $month, int $day )
● void DateTime::setDate ( int $year, int
$month, int $day )

www.intellibitz.com training@intellibitz.com
INTELLI BITZ
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

date_date_set
● Parameters
– object
● DateTime object.
– year
● Year of the date.
– month
● Month of the date.
– day
● Day of the date.
● Return Values
● Returns NULL on success or FALSE on failure.

www.intellibitz.com training@intellibitz.com
INTELLI BITZ
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

date_default_timezone_get
● Gets the default timezone used by all
date/time functions in a script
● string date_default_timezone_get ( void )

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

date_default_timezone_get
– The TZ environment variable (if non empty)
– The date.timezone ini option (if set)
– "magical" guess (if the operating system
supports it)
– If none of the above options succeeds, return
UTC
● Return Values
– Returns a string

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

date_default_timezone_set
● Sets the default timezone used by all
date/time functions in a script
● bool date_default_timezone_set ( string
$timezone_identifier )
● date_default_timezone_set() sets the default
timezone used by all date/time functions.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

date_default_timezone_set
● Parameters
– timezone_identifier
● The timezone identifier, like UTC or Europe/Lisbon.
The list of valid identifiers is available in the Appendix I,
List of Supported Timezones.
● Return Values
– This function returns FALSE if the
timezone_identifier isn't valid, or TRUE
otherwise.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

date_format
● Returns date formatted according to given
format
● string date_format ( DateTime $object, string
$format )
● string DateTime::format ( string $format )

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

date_format
● Parameters
– object
● DateTime object.
– format
– Format accepted by date().
● Return Values
– Returns formatted date on success or FALSE on
failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

date_modify
● Alters the timestamp
● void date_modify ( DateTime $object, string $modify )
● void DateTime::modify ( string $modify )
● Parameters
– object
● DateTime object.

– modify
● String in a relative format accepted by strtotime().

● Return Values
– Returns NULL on success or FALSE on failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

date_offset_get
● Returns the daylight saving time offset
● int date_offset_get ( DateTime $object )
● int DateTime::getOffset ( void )
● Parameters
– object
● DateTime object.
● Return Values
– Returns DST offset in seconds on success or
FALSE on failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

date_parse
● date_parse — Returns associative array with
detailed info about given date
● array date_parse ( string $date )
● Parameters
– date
– Date in format accepted by strtotime().
● Return Values
● Returns array on success or FALSE on
failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

date_parse
<?php
print_r(date_parse("2006-12-12 10:00:00.5"));
?>
The above example will output:
Array
(
[year] => 2006
[month] => 12
[day] => 12
[hour] => 10
[minute] => 0
[second] => 0
[fraction] => 0.5
[warning_count] => 0
[warnings] => Array()
[error_count] => 0
[errors] => Array()
[is_localtime] =>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

date_sun_info
● Returns an array with information about
sunset/sunrise and twilight begin/end
● array date_sun_info ( int $time, float
$latitude, float $longitude )
● Parameters
– time
● Timestamp.
– latitude
● Latitude in degrees.
– longitude
● Longitude in degrees.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

get_sun_info
● Return Values
– Returns array on success or FALSE on failure.
<?php
$sun_info = date_sun_info(strtotime("2006-12-12"), 31.7667, 35.2333);
foreach ($sun_info as $key => $val) {
echo "$key: " . date("H:i:s", $val) . "\n"; The above example will output:
} sunrise: 05:52:11
sunset: 15:41:21
?> transit: 10:46:46
civil_twilight_begin: 05:24:08
civil_twilight_end: 16:09:24
nautical_twilight_begin: 04:52:25
nautical_twilight_end: 16:41:06
astronomical_twilight_begin: 04:21:32
astronomical_twilight_end: 17:12:00

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

date_sunrise
● Returns time of sunrise for a given day and
location
● mixed date_sunrise ( int $timestamp [, int
$format [, float $latitude [, float $longitude [,
float $zenith [, float $gmt_offset]]]]] )
● date_sunrise() returns the sunrise time for a
given day (specified as a timestamp) and
location.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

date_sunrise
● Parameters
– timestamp
● The timestamp of the day from which the sunrise time
is taken.
– latitude
● Defaults to North, pass in a negative value for South.
See also: date.default_latitude
– longitude
● Defaults to East, pass in a negative value for West.
See also: date.default_longitude

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

date_sunrise
● zenith
● Default: date.sunrise_zenith
– gmtoffset
● Specified in hours.
● Return Values
– Returns the sunrise time in a specified format on
success, or FALSE on failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

date_sunrise
Constant description example
SUNFUNCS_RET_STRING returns the result as string 16:46
SUNFUNCS_RET_DOUBLE returns the result as float 16.78243132
SUNFUNCS_RET_TIMESTAMP returns the result as integer (timestamp) 1095034606

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

date_sunrise
<?php
/* calculate the sunrise time for Lisbon, Portugal
Latitude: 38.4 North
Longitude: 9 West
Zenith ~= 90
offset: +1 GMT
*/
echo date("D M d Y"). ', sunrise time : ' .date_sunrise(time(), SUNFUNCS_RET_STRING, 38.4, -9, 90, 1);
?>
The above example will output something similar to:
Mon Dec 20 2004, sunrise time : 08:54

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

date_sunset
● Returns time of sunset for a given day and
location
● mixed date_sunset ( int $timestamp [, int
$format [, float $latitude [, float $longitude [,
float $zenith [, float $gmt_offset]]]]] )
● date_sunset() returns the sunset time for a
given day (specified as a timestamp) and
location.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

date_sunset
● Parameters
– timestamp
● The timestamp of the day from which the sunset time is

taken.
– latitude
● Defaults to North, pass in a negative value for South. See

also: date.default_latitude
– longitude
● Defaults to East, pass in a negative value for West. See

also: date.default_longitude
– zenith
– Default: date.sunrise_zenith
– gmtoffset
– Specified in hours.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

date_sunset
<?php
/* calculate the sunset time for Lisbon, Portugal
Latitude: 38.4 North
Longitude: 9 West
Zenith ~= 90
offset: +1 GMT
*/
echo date("D M d Y"). ', sunset time : ' .date_sunset(time(),
SUNFUNCS_RET_STRING, 38.4, -9, 90, 1);
?>
The above example will output something similar to:
Mon Dec 20 2004, sunset time : 18:13

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

date_time_set
● Sets the time
● void date_time_set ( DateTime $object, int
$hour, int $minute [, int $second] )
● void DateTime::setTime ( int $hour, int
$minute [, int $second] )

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

date_time_set
● Parameters
– object
● DateTime object.
– hour
● Hour of the time.
– minute
● Minute of the time.
– second
● Second of the time.
● Return Values
– Returns NULL on success or FALSE on failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

date_timezone_get
● Return time zone relative to given DateTime
● DateTimeZone date_timezone_get
(DateTime $object)
● DateTimeZone DateTime::getTimezone(void)
● Parameters
● object
– DateTime object.
● Return Values
– Returns DateTimeZone object on success or
FALSE on failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

date_timezone_set
● Sets the time zone for the DateTime object
● void date_timezone_set ( DateTime $object,
DateTimeZone $timezone )
● void DateTime::setTimezone
( DateTimeZone $timezone )
● Parameters
– Object ..DateTime object.
– Timezone ..Desired time zone.
● Return Values

Returns NULL on success or FALSE on failure.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

date
● Format a local time/date
● string date ( string $format [, int
$timestamp] )
● Returns a string formatted according to the
given format string using the given integer
timestamp or the current time if no timestamp
is given. In other words, timestamp is
optional and defaults to the value of time().
● Parameters
● format
– The format of the outputted date string.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

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

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

getdate
● Get date/time information
● array getdate ( [int $timestamp] )
● Returns an associative array containing the
date information of the timestamp, or the
current local time if no timestamp is given.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

getdate
● Parameters
– timestamp
● The optional timestamp parameter is an integer Unix
timestamp that defaults to the current local time if a
timestamp is not given. In other words, it defaults to the
value of time().
● Return Values
– Returns an associative array of information
related to the typestamp.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

getdate
<?php
$today = getdate();
print_r($today);
?>
The above example will output something similar to:
Array
(
[seconds] => 40
[minutes] => 58
[hours] => 21
[mday] => 17
[wday] => 2
[mon] => 6
[year] => 2003
[yday] => 167
[weekday] => Tuesday
[month] => June
[0] => 1055901520
)

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

gettimeofday
● Get current time
● mixed gettimeofday ( [bool $return_float] )
● This is an interface to gettimeofday(2). It
returns an associative array containing the
data returned from the system call.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

gettimeofday
● Parameters
– return_float
● When set to TRUE, a float instead of an array is
returned.
● Return Values
– By default an array is returned. If return_float is
set, then a float is returned.
● Array keys:
– "sec" - seconds since the Unix Epoch
– "usec" - microseconds
– "minuteswest" - minutes west of Greenwich
– "dsttime" - type of dst correction

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

gettimeofday
<?php
print_r(gettimeofday());

echo gettimeofday(true);
?>
The above example will output something similar to:
Array
(
[sec] => 1073504408
[usec] => 238215
[minuteswest] => 0
[dsttime] => 1
)
1073504408.23910

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

gmdate
● Format a GMT/UTC date/time
● string gmdate ( string $format [, int
$timestamp] )
● Identical to the date() function except that the
time returned is Greenwich Mean Time
(GMT).

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

gmdate
● Parameters
– format
● The format of the outputted date string. See the
formatting options for the date() function.
– timestamp
● The optional timestamp parameter is an integer Unix
timestamp that defaults to the current local time if a
timestamp is not given. In other words, it defaults to the
value of time().
● Return Values
– Returns a formatted date string. If a non-numeric value is used
for timestamp, FALSE is returned and an E_WARNING level
error is emitted.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

gmdate

When run in Finland (GMT +0200), the first line below prints "Jan 01 1998 00:00:00", while the second
prints "Dec 31 1997 22:00:00".
<?php
echo date("M d Y H:i:s", mktime(0, 0, 0, 1, 1, 1998));
echo gmdate("M d Y H:i:s", mktime(0, 0, 0, 1, 1, 1998));
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

CHAPTER 14

CALENDER FUNCTIONS

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Calendar functions
● The calendar extension presents a series of functions to
simplify converting between different calendar formats.
● The intermediary or standard it is based on is the Julian Day
Count. The Julian Day Count is a count of days starting from
January 1st, 4713 B.C.
● To convert between calendar systems, you must first convert
to Julian Day Count, then to the calendar system of your
choice. Julian Day Count is very different from the Julian
Calendar!

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

cal_days_in_month
● cal_days_in_month — Return
the number of days in a <?php

month for a given year and $num =


cal_days_in_month(CAL_GREGORIA
calendar N, 8, 2003); // 31
● int cal_days_in_month ( int echo "There was $num days in August
2003";
$calendar, int $month, int
$year ) ?>

● This function will return the


number of days in the month
of year for the specified
calendar.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

cal_from_jd
<?php
● cal_from_jd — Converts from $today = unixtojd(mktime(0, 0, 0, 8, 16, 2003));
Julian Day Count to a
print_r(cal_from_jd($today,
supported calendar CAL_GREGORIAN));
● array cal_from_jd ( int $jd, int ?>
$calendar ) The above example will output:
● cal_from_jd() converts the Array
Julian day given in jd into a (
date of the specified calendar. [date] => 8/16/2003
[month] => 8
Supported calendar values are [day] => 16
CAL_GREGORIAN, [year] => 2003
[dow] => 6
CAL_JULIAN, CAL_JEWISH [abbrevdayname] => Sat
and CAL_FRENCH. [dayname] => Saturday
[abbrevmonth] => Aug
[monthname] => August
)

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

cal_info
● cal_info — Returns information about a particular calendar
● Description
● array cal_info ( [int $calendar] )
● cal_info() returns information on the specified calendar.
● Calendar information is returned as an array containing the elements
calname, calsymbol, month, abbrevmonth and maxdaysinmonth. The
names of the different calendars which can be used as calendar are as
follows:
● * 0 or CAL_GREGORIAN - Gregorian Calendar
● * 1 or CAL_JULIAN - Julian Calendar
● * 2 or CAL_JEWISH - Jewish Calendar
● * 3 or CAL_FRENCH - French Revolutionary Calendar
● If no calendar is specified information on all supported calendars is
returned as an array. This functionality is available beginning with PHP
5.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

call_info
Array
<?php (
[months] => Array
$info = cal_info(0); ( [abbrevmonths] => Array
print_r($info); [1] => January (
[2] => February [1] => Jan
?> [3] => March [2] => Feb
[4] => April [3] => Mar
[5] => May [4] => Apr
[6] => June [5] => May
[7] => July [6] => Jun
[8] => August [7] => Jul
[9] => September [8] => Aug
[10] => October [9] => Sep
[11] => November [10] => Oct
[12] => December [11] => Nov
) [12] => Dec
)
[maxdaysinmonth] => 31
[calname] => Gregorian
[calsymbol] => CAL_GREGORIAN
)

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

cal_to_jd
● cal_to_jd — Converts from a supported calendar to Julian
Day Count
● int cal_to_jd ( int $calendar, int $month, int $day, int $year )
● cal_to_jd() calculates the Julian day count for a date in the
specified calendar. Supported calendars are
CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH and
CAL_FRENCH.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

easter_date
● easter_date — Get Unix timestamp<?php
for midnight on Easter of a given
year echo date("M-d-Y", easter_date(1999)); //
Apr-04-1999
● int easter_date ( [int $year] )
● Returns the Unix timestampecho date("M-d-Y", easter_date(2000));
Apr-23-2000
//

corresponding to midnight on
echo date("M-d-Y", easter_date(2001)); //
Easter of the given year. Apr-15-2001
● Since PHP 4.3.0, the year
parameter is optional and defaults?>
to the current year according to the
localtime if omitted.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

easter_days
● easter_days — Get number of days after March 21 on which Easter falls
for a given year
● int easter_days ( [int $year [, int $method]] )
● Returns the number of days after March 21 on which Easter falls for a
given year. If no year is specified, the current year is assumed.
● Since PHP 4.3.0, the year parameter is optional and defaults to the
current year according to the localtime if omitted.
● The method parameter was also introduced in PHP 4.3.0 and allows to
calculate easter dates based on the Gregorian calendar during the years
1582 - 1752 when set to CAL_EASTER_ROMAN. See the calendar
constants for more valid constants.
● This function can be used instead of easter_date() to calculate Easter
for years which fall outside the range of Unix timestamps (i.e. before
1970 or after 2037).

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

easter_days

<?php

echo easter_days(1999); // 14, i.e. April 4


echo easter_days(1492); // 32, i.e. April 22
echo easter_days(1913); // 2, i.e. March 23

?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

FrenchToJD
● FrenchToJD — Converts a date from the French Republican
Calendar to a Julian Day Count
● int frenchtojd ( int $month, int $day, int $year )
● Converts a date from the French Republican Calendar to a
Julian Day Count.
● These routines only convert dates in years 1 through 14
(Gregorian dates 22 September 1792 through 22 September
1806). This more than covers the period when the calendar
was in use.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

GregorianToJD
● GregorianToJD — Converts a Gregorian date to Julian Day
Count
● int gregoriantojd ( int $month, int $day, int $year )
● Valid Range for Gregorian Calendar 4714 B.C. to 9999 A.D.
● Although this function can handle dates all the way back to
4714 B.C., such use may not be meaningful. The Gregorian
calendar was not instituted until October 15, 1582 (or October
5, 1582 in the Julian calendar). Some countries did not
accept it until much later. For example, Britain converted in
1752, The USSR in 1918 and Greece in 1923. Most
European countries used the Julian calendar prior to the
Gregorian.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

JDDayOfWeek
● JDDayOfWeek — Returns the day of the week
● mixed jddayofweek ( int $julianday [, int $mode] )
● Returns the day of the week. Can return a string or an integer
depending on the mode.

MODE MEANING
0 (Default) Returns the day number as an int (0=Sunday, 1=Monday, etc)
1 Returns string containing the day of week (English-Gregorian)
2 Returns a string containing the abbreviated day of week (English-Gregorian)

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

JDMonthName
● JDMonthName — Returns a month name
● string jdmonthname ( int $julianday, int $mode )
● Returns a string containing a month name. mode tells this
function which calendar to convert the Julian Day Count to,
and what type of month names are to be returned.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

String functions
Mode Meaning Values
0 Gregorian – abbreviated Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct,Nov, Dec

1 Gregorian January, February, March, April, May, June, July, August,


September, October, November, December

2 Julian - abbreviated Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
3 Julian January, February, March, April, May, June, July, August, September,
October, November, December

4 Jewish Tishri, Heshvan, Kislev, Tevet, Shevat, AdarI, AdarII, Nisan, Iyyar,
Sivan, Tammuz, Av, Elul
5 French Republican Vendemiaire, Brumaire, Frimaire, Nivose, Pluviose, Ventose,
Germinal, Floreal, Prairial, Messidor, Thermidor, Fructidor, Extra

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

JDToFrench
● JDToFrench — Converts a Julian Day Count
to the French Republican Calendar
● string jdtofrench ( int $juliandaycount )
● Converts a Julian Day Count to the French
Republican Calendar.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

JDToGregorian
● JDToGregorian — Converts Julian Day
Count to Gregorian date
● string jdtogregorian ( int $julianday )
● Converts Julian Day Count to a string
containing the Gregorian date in the format
of "month/day/year".

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

jdtojewish
● jdtojewish — Converts a Julian day count to a Jewish
calendar date
● string jdtojewish(int $juliandaycount[,bool$hebrew [, int $fl]] )
● Converts a Julian Day Count to the Jewish Calendar.
● The optional hebrew and fl parameters became available in
PHP 5.0.0
● If the hebrew parameter is set to TRUE, the fl parameter is
used for Hebrew, string based, output format. The available
formats are: CAL_JEWISH_ADD_ALAFIM_GERESH,
CAL_JEWISH_ADD_ALAFIM,CAL_JEWISH_ADD_GERESH
AYIM.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

JDToJulian
● JDToJulian — Converts a Julian Day Count
to a Julian Calendar Date
● string jdtojulian ( int $julianday )
● Converts Julian Day Count to a string
containing the Julian Calendar Date in the
format of "month/day/year".

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

jdtounix
● jdtounix — Convert Julian Day to Unix
timestamp
● int jdtounix ( int $jday )
● This function will return a Unix timestamp
corresponding to the Julian Day given in jday
or FALSE if jday is not inside the Unix epoch
(Gregorian years between 1970 and 2037 or
2440588 <= jday <= 2465342 ).
The time returned is localtime (and not GMT).

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

JewishToJD
● JewishToJD — Converts a date in the Jewish Calendar
to Julian Day Count
● int jewishtojd ( int $month, int $day, int $year )
● Although this function can handle dates all the way back
to the year 1 (3761 B.C.), such use may not be
meaningful. The Jewish calendar has been in use for
several thousand years, but in the early days there was
no formula to determine the start of a month. A new
month was started when the new moon was first
observed.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

JulianToJD
● JulianToJD — Converts a Julian Calendar date to Julian Day
Count
● int juliantojd ( int $month, int $day, int $year )
● Valid Range for Julian Calendar 4713 B.C. to 9999 A.D.
● Although this function can handle dates all the way back to
4713 B.C., such use may not be meaningful. The calendar
was created in 46 B.C., but the details did not stabilize until at
least 8 A.D., and perhaps as late at the 4th century. Also, the
beginning of a year varied from one culture to another - not all
accepted January as the first month.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

unixtojd
● unixtojd — Convert Unix timestamp to Julian Day
● Description
● int unixtojd ( [int $timestamp] )

● Return the Julian Day for a Unix timestamp (seconds since


1.1.1970), or for the current day if no timestamp is given.

www.intellibitz.com training@intellibitz.com
CHAPTER 15

CLASSES AND OBJECTS

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Classes and Objects


● Object basics.
● Defining classes
● Creating new objects.
● Creating constructors.
● Accessing properties and methods.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Object Basics
● An OBJECT is a structure that combines
data about a thing, with actions on that thing.
● The CLASS describes and holds the
variables and functions for a kind of object.
● The METHOD is the function defined in the
class.
● The PROPERTY is the variable defined in
the class.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

PHP and OOP


● OOP is a particular approach to solving
problem that is not necessarily tied to any
language or hardware architecture.
● PHP is inherently a procedural language that
has added the syntax necessary to support
solution using OOP technique.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Defining Classes
● The special form class,followed by the name
of the class.
● An optional extensional clause, extends and
then the name of the class that should be
inherited from.
● A set of braces containing the variable
declaration and function definitions.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Defining Classes
● The variable declaration starts with special
form var which is followed by conventional
$variable name.
● The variable declarations in a class can also
have an initial assignments to a constant
value.
● The functions defined in a class are local to
the class.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Creating new objects


● An Object is an instance of a class and the
act of creating object from a class is called
instantiation.
● The objects can be created with new
keyword.
● $objectname = new classname();
● $objectname is the instance of the class
classname.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Creating new object


● We can invokeor acces the member
variables and functions in the class using ->
operator
● $objectname ->functionname();

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

__autoload()
● It is common OOP practice to place each of
your class definition into separate files.
● It is good practice to group various class
definition into multiple files based on their
usage.
● By doing this you don't need to include one
large library file in every page.
● You only need to include the files containing
the specific classes that page needs.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

__autoload()
● You can define __ Assum e thatyou nam e allyourclass files in the follow ing schem e .
class-{ classnam e.php }
autoload function the follow ing exam ple show s youhow to m ake those files
that automatically be autom atically loaded.
called any time a << ?php
?php
function __ autoload ($classnam e )
new object attempts {
require _ once “class-{ $classnam e } .php”;
to be instantiated. }
//instantiate an objectofclass 'cd '
// this w illm ake ittry to load the file :class-cd .php
$m ydisk= new cd ();
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Constructors
● Constructor function sets up the initial state
of a new object before it is used.
● Constructors are used to initialize the
member variables in the class.
● Classes which have a constructor method
call this method on each newly-created
object

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Constructors
● PHP5 allows you to declare a constructor
method by including the member function
__construct() .
● You can also define a constructor by method
by including a function with same name as
the class.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Magic functions
● PHP reserves for itself any function with
double underscores prefix(__)as magic
functions.
● This provides various automatic features.
● Do not make any of your own functions have
a double underscore,unless you specially
wnt to invoke one of this magic functions.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming

Destructors
TD_PHP_V1.0.0

● The destructor method will be called as soon


as all references to a particular object are
removed or when the object is explicitly
destroyed with a call to unset().
● Unlike __construct() function __destruct ()
function can't be defined to take any
parameter.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Private members
● The variables and functions in the class can
be declared as private.
● The private variables and functions can be
accessed only by the code within the class.
● An attempt to access the private variables
and functions outside the class gives an
error.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Protected members
● Protected is used for members which are
internal to the object's logic ,but where it
might make sense for inheriting classes to
override them.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Defining some time and date handling
vocabulary such as epoch timestamp, time
and date parts and formatted date and time
string.
● Printing formatted time and date string with
strftime( ) and date( ).
● Making an epoch timestamp with mktime ( ).

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter summary
● Making an epoch timestamp with strtotime().
● Displaying form elements to allow for date or
time input.

www.intellibitz.com training@intellibitz.com
CHAPTER 16

CLASSES AND OBJECTS


FUNCTIONS

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

classes/object functions
● These functions allow you to obtain information
about classes and instance objects.
● You can obtain the name of the class to which
an object belongs,as well as its member
properties and methods.
● Using these functions, you can find out not only
the class membership of an object, but also its
parentage (i.e. what class is the object class
extending).

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Classes objects

<?php
// base class with member properties and methods function is_edible()

class Vegetable { {

var $edible; return $this->edible;

var $color; }

function Vegetable($edible, $color="green") function what_color()

{ {

$this->edible = $edible; return $this->color;

$this->color = $color; }

} } // end of class Vegetable

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Classes objects

function is_cooked()
// extends the base class
{
class Spinach extends Vegetable {
return $this->cooked;
var $cooked = false;
}
function Spinach()
} // end of class Spinach
{
?>
$this->Vegetable(true, "green");
}
function cook_it()
{
$this->cooked = true;
}

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Classes object
● In this example, we first define a base class
and an extension of the class. The base
class describes a general vegetable, whether
it is edible or not and what is its color. The
subclass Spinach adds a method to cook it
and another to find out if it is cooked.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

call_user_method
● call_user_method — Call a user method on
an specific object [deprecated]
● Description
● mixed call_user_method ( string
$method_name, object &$obj [, mixed
$parameter [, mixed $...]] )

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

call_user_method_array
● call_user_method_array — Call a user
method given with an array of parameters
[deprecated]
● Description
● mixed call_user_method_array ( string
$method_name, object &$obj, array
$paramarr )

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

class_exists
● class_exists — Checks if the class has been defined
● bool class_exists ( string $class_name [, bool $autoload] )
● This function checks if the given class have been defined.
● Parameters
– class_name
● The class name

– autoload
● Whether to call __autoload or not by default

● Return Values
– Returns TRUE if class_name is a defined class, FALSE
otherwise.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

class_exists
<?php //autoload parameter example
<?php
function __autoload($class)
// Check the class exists before trying to
{ include($class . '.php'); use it
// Check to see if the include declared the class if (class_exists('MyClass')) {
if (!class_exists($class, false)) { $myclass = new MyClass(); } ?>
trigger_error("Unable to load class: $class", E_USER_WARNING);
}
}
if (class_exists('MyClass')) {
$myclass = new MyClass();
}
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

get_class_methods
● get_class_methods — Gets the class methods'
names
● array get_class_methods ( mixed $class_name )
● Gets the class methods names.
● Parameters
– class_name
● The class name of an object instance

● Return Values
– Returns an array of method names defined for
the class specified by class_name. In case of an
error, it returns NULL.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

get_class_methods
<?php
class myclass {
// method 2
// constructor $class_methods = get_class_methods('myclass');
function myfunc2()
function myclass() // or
{
{ $class_methods = get_class_methods(new
return(true); myclass());
return(true);
} foreach ($class_methods as $method_name) {
}
echo "$method_name\n";
// method 1
}
function myfunc1()
?>
{
The above example will output:
return(true);
myclass
} } myfunc1
myfunc2

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

get_class_vars
● get_class_vars — Get the default properties of the class
● array get_class_vars ( string $class_name )
● Get the default properties of the given class.
● Parameters
– class_name
● The class name

● Return Values
– Returns an associative array of default public
properties of the class. The resulting array elements
are in the form of varname => value.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

<?php
get_class_var
$my_class = new myclass();
class myclass {
$class_vars = get_class_vars(get_class($my_class));
var $var1; // this has no default value...
foreach ($class_vars as $name => $value) {
var $var2 = "xyz";
echo "$name : $value\n";
var $var3 = 100;
}
private $var4; // PHP 5
// constructor
?>
function myclass() {
The above example will output:
// change some properties
// Before PHP 4.2.0
$this->var1 = "foo"; var2 : xyz
var3 : 100
$this->var2 = "bar";
// As of PHP 4.2.0
return true; var1 :
var2 : xyz
} } var3 : 100

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

get_class
● get_class — Returns the name of the class of an object
● string get_class ( [object $object] )
● Gets the name of the class of the given object.
● Parameters
– object
● The tested object

● Return Values
– Returns the name of the class of which object is an
instance. Returns FALSE if object is not an object.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

get_class
<?php // create an object
class foo { $bar = new foo();
function foo() // external call
{ echo "Its name is " , get_class($bar) , "\n";
// implements some logic // internal call
} $bar->name();
function name() ?>
{
echo "My name is " , get_class($this) , "\n";
The above example will output:
}
Its name is foo
} My name is foo

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

get_declared_classes
● get_declared_classes — Returns an array with the name
of the defined classes
● array get_declared_classes ( void )
● Gets the declared classes.
● Return Values
– Returns an array of the names of the declared
classes in the current script.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

get_declared_classes
● Note: In PHP 4.0.1, three extra classes are <?php
returned at the beginning of the array: print_r(get_declared_classes());
stdClass (defined in Zend/zend.c),
?>
OverloadedTestClass (defined in
ext/standard/basic_functions.c) and The above example will output
something similar to:
Directory (defined in ext/standard/dir.c).
● Also note that depending on what libraries Array
(
you have compiled into PHP, additional [0] => stdClass
classes could be present. This means that [1] =>
you will not be able to define your own __PHP_Incomplete_Class
classes using these names. There is a list of [2] => Directory
predefined classes in the Predefined )
Classes section of the appendices.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

get_declared_interfaces
● get_declared_interfaces — Returns an array
of all declared interfaces
● array get_declared_interfaces ( void )
● Gets the declared interfaces.
● Return Values
– Returns an array of the names of the declared
interfaces in the current script.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

get_declared_interfaces

<?php
print_r(get_declared_interfaces());
?>
The above example will output something similar to:
Array
(
[0] => Traversable
[1] => IteratorAggregate
[2] => Iterator
[3] => ArrayAccess
[4] => reflector
[5] => RecursiveIterator
[6] => SeekableIterator
)

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

get_object_vars
● get_object_vars — Gets the properties of the given object
● array get_object_vars ( object $object )
● Gets the properties of the given object.
● Parameters
– object
● An object instance.

– Return Values
● Returns an associative array of defined object

properties for the specified object. If a property have


not been assigned a value, it will be returned with a
NULL value.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

get_object_vars
<?php print_r(get_object_vars($p1));
function getPoint()
class Point2D { $p1->setLabel("point #1");
{
var $x, $y; print_r(get_object_vars($p1));
return array("x" => $this->x,
var $label; ?>
"y" => $this->y,
function Point2D($x, $y)
"label" => $this->label);
{ The above example will output:
} Array
$this->x = $x;
(
} [x] => 1.233
$this->y = $y;
[y] => 3.445
} // "$label" is declared but not [label] =>
)
defined Array
(
$p1 = new Point2D(1.233,
[x] => 1.233
function setLabel($label) 3.445); [y] => 3.445
{ [label] => point #1
)
$this->label = $label;
}
www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

get_parent_class
● get_parent_class — Retrieves the parent class name for
object or class
● string get_parent_class ( [mixed $object] )
● Retrieves the parent class name for object or class.
● Parameters
– object
● The tested object or class name

● Return Values
– Returns the name of the parent class of the class of which
object is an instance or the name.
● If called without parameter outside object, this function
returns FALSE.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

<?php
get_parent_class
class dad {
class child2 extends dad {
function dad()
function child2()
{
{
// implements some logic
echo "I'm " ,
} get_parent_class('child2') , "'s son
too\n";
}
}
class child extends dad {
}
function child()
$foo = new child(); The above example will
{
output:
$bar = new child2();
echo "I'm " , get_parent_class($this) ,
I'm dad's son
"'s son\n";
I'm dad's son too
} ?>
}

www.intellibitz.com training@intellibitz.com
training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

interface_exists
● interface_exists — Checks if the interface has been defined
● bool interface_exists ( string $interface_name [, bool
$autoload] )
● Checks if the given interface has been defined.
● Parameters
– interface_name
● The interface name
– autoload
● Wether to call __autoload or not by default
– Return Values
● Returns TRUE if the interface given by interface_name

has been defined, FALSE otherwise.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

interface_exists
<?php
// Check the interface exists before trying to
use it
if (interface_exists('MyInterface')) {
class MyClass implements MyInterface
{
// Methods
}
}

?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

is_a
● is_a — Checks if the object is of this class or has this class
as one of its parents
● bool is_a ( object $object, string $class_name )
● Checks if the given object is of this class or has this class as
one of its parents.
● Note: The is_a() function is deprecated as of PHP 5 in
favor of the instanceof type operator.
● Parameters
– object
● The tested object
– class_name
● The class name

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

is_a
<?php
<?php
● Return Values // define a class
● Returns if ($WF instanceof WidgetFactory) {
class WidgetFactory
TRUE if the {
echo 'Yes, $WF is a WidgetFactory';

object is of var $oink = 'moo';


}
this class or }
?>
has this // create a new object
class as
$WF = new WidgetFactory();
one of its
if (is_a($WF, 'WidgetFactory'))
parents, {
FALSE echo "yes, \$WF is still a
otherwise. WidgetFactory\n";
}
?>

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

is_subclass_of
● is_subclass_of — Checks if the object has this class as one of its
parents
● bool is_subclass_of ( mixed $object, string $class_name )
● Checks if the given object has the class class_name as one of its
parents.
● Parameters
– Object
● A class name or an object instance

– class_name
● The class name
– Return Values
● This function returns TRUE if the object object, belongs to a

class which is a subclass of class_name, FALSE otherwise.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

is_subclass_of
// create a new object
<?php
$WF = new WidgetFactory();
// define a class
$WFC = new WidgetFactory_Child();
class WidgetFactory
if (is_subclass_of($WFC, 'WidgetFactory')) {
{
echo "yes, \$WFC is a subclass of WidgetFactory\n";
var $oink = 'moo';
} else {
}
echo "no, \$WFC is not a subclass of WidgetFactory\n";
// define a child class
}
class WidgetFactory_Child
extends WidgetFactory if (is_subclass_of($WF, 'WidgetFactory')) {
{ echo "yes, \$WF is a subclass of WidgetFactory\n";
var $oink = 'oink'; } else {
} echo "no, \$WF is not a subclass of WidgetFactory\n";
}

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

is_sub_class_of
// usable only since PHP 5.0.3
if (is_subclass_of('WidgetFactory_Child', 'WidgetFactory')) {
echo "yes, WidgetFactory_Child is a subclass of WidgetFactory\n";
} else {
echo "no, WidgetFactory_Child is not a subclass of WidgetFactory\n";
}
?>
The above example will output:
yes, $WFC is a subclass of WidgetFactory
no, $WF is not a subclass of WidgetFactory
yes, WidgetFactory_Child is a subclass of
WidgetFactory

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

method_exists
● method_exists — Checks if the class method
exists
● bool method_exists ( object $object, string
$method_name )
● Checks if the class method exists in the
given object.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

method_exists
<?php
$directory = new Directory('.');
● Parameters var_dump(method_exists($directory,'read'))
– object ;
?>
● An object instance
The above example will output:
– method_name bool(true)
● The method name
– Return Values
● Returns TRUE if the method given by method_name
has been defined for the given object, FALSE
otherwise.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

property_exists
● property_exists — Checks if the object or class has a property
● Description
● bool property_exists ( mixed $class, string $property )
● This function checks if the given property exists in the specified class
(and if it is accessible from the current scope).
● Note: As opposed with isset(), property_exists() returns TRUE even if
the property has the value NULL.
● Parameters
– Class - - The class name or an object of the class to test for
– Property - - The name of the property
● Return Values
– Returns TRUE if the property exists, FALSE if it doesn't exist or
NULL in case of an error.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

property_exists
<?php
class myClass {
public $mine;
private $xpto;
static function test() {
var_dump(property_exists('myClass', 'xpto')); // true, it can be accessed from here
}
}
var_dump(property_exists('myClass', 'mine')); //true
var_dump(property_exists(new myClass, 'mine')); //true
var_dump(property_exists('myClass', 'xpto')); //false, isn't public
myClass::test();
?>

www.intellibitz.com training@intellibitz.com
CHAPTER 17

WORKING WITH FILES

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Working with Files


● Understanding File Permissions
● Reading and Writing Entire Files
● Reading and Writing Parts of Files
● Working with CSV Files
● Inspecting File Permissions
● Sanitizing Externally Supplied Filenames

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Understanding File Permissions


● PHP can open a remote file as easy as you
can open a local file
● PHP interpreter running inside a webserver,
has the privileges of the webserver account
● The web server (and the PHP interpreter)
need to be able to read all PHP program files
that make your website, but they shouldn't be
able to change them

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Reading and Writing Entire Files


● Use file_get_contents() to read the contents
of a file into a string
● A local and remote file look the same to
file_get_contents()
● Use file_put_contents() to write a string to a
file
● The kinds of URL that are acceptable to
file_put_contents() are more limited

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Reading and Writing part of


Files
● Use fopen(), fgets(), feof(), and fclose()
● $fh = fopen ('/home/user/test.txt', 'rb');
● Use fwrite() to write to a file.. fwrite() doesn't
automatically add a newline on to the end of
the string you write
● Use fgetcsv() to read a line of CSV file
● Comma separated value file is a type of file
that stores tabular data.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Inspecting File Permissions


● Use file_exists() to check if file exists
● Use is_readable() or is_writeable() before
retrieving its contents with file_get_contents()
● Use $php_errormsg global variable to track
error messages (track_errors must be on)
● Use identical operator === to compare for
same value and same type

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Sanitizing Filenames
● Special characters must be escaped
● In filenames the special characters are /
(separates filenames) and .. (go up one
directory)
● Use realpath() to translate obfuscated
filename into the real names

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Understanding where the PHP interpreter's
file access permissions come from
● Reading and writing entire local and remote
files with file_get_contents()
● Opening and closing files with fopen() and
fclose()
● Reading a line of a file with fgets()

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Using feof() and a for() loop to read each line
in a file
● Using forward slashes in filenames with all
operating systems
● Providing different file modes to fopen()
● Writing data to a file with fwrite ()
● Reading a line of a CSV file with fgetcsv ()

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Determining a file exists with file_exists()
● Inspecting file permissions with is_readable()
and is_writeable()
● Checking for errors returned from file access
functions
● Understanding when to check a return value
with the identical operator (===)
● Sanitizing externally supplied filenames

www.intellibitz.com training@intellibitz.com
CHAPTER 18

GETTEXT FUNCTIONS

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

GETTEXT FUNCTIONS
● The gettext functions implement an NLS
(Native Language Support) API which can be
used to internationalize your PHP
applications.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

dcgettext
● dcgettext — Overrides the domain for a single lookup
● string dcgettext ( string $domain, string $message, int
$category )
● This function allows you to override the current domain for a
single message lookup.
● Parameters
– domain
● The domain

– message
● The message

– Category Return Values


● The category
A string on success.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

dcngettext
● dcngettext — Plural version of dcgettext
● string dcngettext ( string $domain, string $msgid1, string
$msgid2, int $n, int $category )
● This function allows you to override the current domain for a
single plural message lookup.
● Parameters
– domain
● The domain

– msgid1
– msgid2 Return Values
– n A string on success.
– Category

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

dgettext
● dgettext — Override the current domain
● Description
● string dgettext ( string $domain, string $message )

● The dgettext() function allows you to override the current


domain for a single message lookup.
● Parameters
● Domain
– The domain
● message
– The message Return Values
A string on success.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

dngettext
● dngettext — Plural version of dgettext
● string dngettext ( string $domain, string $msgid1, string
$msgid2, int $n )
● The dngettext() function allows you to override the current
domain for a single plural message lookup.
● Parameters
– Domain
● The domain

– msgid1 Return Values


– msgid2 A string on success.
– n

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

gettext
● gettext — Lookup a message in the current domain
● string gettext ( string $message )
● Looks up a message in the current domain.
● Parameters
– message
● Return Values
– Returns a translated string if one is found in the translation
table, or the submitted message if not found.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

ngettext
● ngettext — Plural version of gettext
● string ngettext ( string $msgid1, string $msgid2, int $n )
● The plural version of gettext(). Some languages have more
than one form for plural messages dependent on the count.
● Parameters
– msgid1
– msgid2
– n
● Return Values
– Returns correct plural form of message identified by
msgid1 and msgid2 for count n.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

textdomain
● textdomain — Sets the default domain
● string textdomain ( string $text_domain )
● This function sets the domain to search within when calls are
made to gettext(), usually the named after an application.
● Parameters
– text_domain
● The new message domain, or NULL to get the current

setting without changing it


● Return Values
– If successful, this function returns the current message
domain, after possibly changing it.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

CHAPTER 19

REGULAR EXPRESSION

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Regular expression
● A regular expression, often called as
pattern,is an expression that describes a set
of string.
● Regular expressions are used to test the
sequence of characters (may be in a credit
card number, mobile number,Email
address)has an allowed pattern of
characters.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Regex which you use already


● Search and replace in word processors.
● Directory listing
– dir *.eexe
– dir *.*
– dir sales04???.xls
– Online searching
● In production of code completion systems
and syntax highlighting in integrated
development environments(IDEs).

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Regex can be used for


● Finding doubled words
● Checking inputs from web forms
● Changing date formats
● Finding incorrect case.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Matching characters
● The simplest regular expression involves
matching a single character.
● Most characters and letters mostly match
themselves.
● For example,the regular expression test will
match the string “test” exactly.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Metacharacters
● Some characters do not match themselves
and are called metacharacters.
● .^*+?{[]}\|() is the complete list of
metacharacters.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Metacharacters
● “[“ , ”]” are used for specifying a character
class,which is a set of character that you
wish to match.
● Characters can be listed individually or a or a
range of characters can be indicated by
giving two characters and separating them
by a “-”
● Example [abc] is equivalent to [a-c] will
match any of the characters “a,”b” or”c”

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Metacharacters
● ^ matches a start of the line
● [^] matches a single character that is not
contained within the bracket.
● $ matches the end of the line.
● Metacharacters are not active inside classes.
– For example [akm$] will match any of the
characters “a,”k”,”m” or “$”.$ is a metacharacter
but inside the character class it stripped of its
special nature.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Metacharacters
● \ is used to strip the special meaning of
metacharacters.
– For example [asd\[cdf] here “[“ needed to match
inside character class so \ is used to escape [
● \d matches any decimal digits.[0-9]
● \D Matches any non digit character[^0-9]
● \s matches any white space character[
\t\n\r\f\v]

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Metacharacters
● \S matches any non white space characters
[^ \t\n\r\f\v]
● \w matches any alphanumeric character.
[a-zA-Z0-9_]
● \W matches any non alphanumeric
character.
– For example [\s.,] will match any white apace
character or “,” or “.”

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Metacharacters
● . matches any thing except new line
character.
● | A vertical bar separates alternatives.
– For example “gray|grey” ,which could be
shortened to the equivalent gr(a|e)y, can match
gray or grey
● () parentheses are used to define the scope
and precedence of operator.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Quantifier
● A quantifier after a character or group
specifies how often that preceding
expression is allowed to occur.
● The most common quantifiers are ?,* and +

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Quantifier
● ? The ? Indicates there is 0 or 1 of previous
expression.
– For example , “colou?r “ matches both color and
colour.
● * The * indicates there are 0,1 or any of the
previous expression .
– For example “go*gle” matches
ggle,gogle,google,gooogle etc.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Quantifier
● + The plus sign indicates that there is at least
1 of the previous expression
– For example “go+gle “ matches
gogle,google,gooogle etc

The pattern “((great)*grand)?((fa|mo)ther)” matches any ancestor


: father,mother ,grand father,grandmother,great grand father,great
grand mother,great great grand father, great great grand mother.

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Metacharacter
● {m,n} specifies occurrence of the character
minimum of m times and maximum of n
times.
– “ab{2,3}” matches abb or abbb

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

CHAPTER 20

DEBUGGING

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Debugging
● Controlling where errors appear
● Fixing parse errors
● Inspecting program data
● Fixing database errors

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming

Controlling Where Errors


TD_PHP_V1.0.0

Appear
● Programs rarely work correctly the first time
● Use display_errors configuration directive to
make error messages display in browser
● Use log_errors to On to send errors to the
web server error log
● Parse error, Fatal error, Warning, Notice and
Strict notices are the different kinds of errors

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Fixing Parse Errors


● The PHP interpreter is really picky but not
very chatty
● Use PHP-aware editors with syntax
highlighting turned on
● Error messages use tokens
● http://www.php.net/tokens Contains the list of
all tokens that PHP interpreter uses

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Inspecting Program Data


● A program can be syntactically correct but
logically flawed.. adding checkpoint to
display values of variables
● Use diagnostic print statements
● Use var_dump() to include array in output
● Make sure to edit the right file.. use
__FILE__ special constant to check filename
● ob_start(), ob_get_contents(), ob_end_clean

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Fixing Database Errors


● Use setErrorHandling() with
PEAR_ERROR_CALLBACK
● $db->setErrorHandling
(PEAR_ERROR_CALLBACK, 'my_func');
● The callback function must accept one
argument, which is the error object
● Invoke getDebugInfo () to get more error info

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Configuring error display for a web browser,
a web server error log, or both
● Configuring the PHP interpreter's error-
reporting level
● Getting the benefits of a PHP-aware text
editor
● Deciphering parse error messages
● Finding and fixing parse errors

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Printing debugging information with print,
var_dump() and error_log()
● Sending var_dump() output to the error log
with output buffering functions
● Writing a custom database error-handling
function

www.intellibitz.com training@intellibitz.com
CHAPTER 21

WHAT ELSE WITH PHP

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

What Else with PHP?


● Graphics and PDF
● Shockwave/Flash
● Sending and Receiving Mail
● Uploading Files in Forms
● HTML_QuickForm Form-Handling framework
● Classes and Objects
● SQLite
● Advanced XML Processing

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

What Else with PHP?


● Running Shell Commands
● Encryption
● Talking to Other Languages
● IMAP, POP3, and NNTP
● Command-Line PHP
● PHP-GTK

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Even More with PHP!


● More extensions, add-ons, library and built-in
functions are available
● The PHP Manual http://www.php.net/manual
● The PEAR Package List
http://pear.php.net/packages.php
● The PECL Package List
http://pecl.php.net/packages.php

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

Chapter Summary
● Printing debugging information with print,
var_dump() and error_log()
● Sending var_dump() output to the error log
with output buffering functions
● Writing a custom database error-handling
function

www.intellibitz.com training@intellibitz.com
INTELLIBITZ
Technologies
PHP Web Programming
TD_PHP_V1.0.0

IntelliBitz Technologies
Training Division
168, Medavakkam Main Road
Madipakkam, Chennai 91.
PH: +91 044 2247 5106
www.intellibitz.com
training@intellibitz.com
www.intellibitz.com training@intellibitz.com

Das könnte Ihnen auch gefallen