A PHP built - in function is a self-contained segment of code which
performs a certain task. Often times, but not always, a function will
accept parameters -- or values pass to the function which it uses
-- and will return a value such as the result of its operations.
Functions are a very important way to segregate and enclose specific
tasks, especially tasks which may be called upon repeatedly from different
statements in a page.
Learning Objectives
The purpose of this lesson is to introduce you to PHP’s
functions and discuss techniques for writing clean, manageable scripts,
more compact and that is easier to read. At the end of this lesson, you
will understand everything about:
Using PHP’s
built-in variables
Handling
strings
Working with
arrays
Keeping your
code tidy
Understanding
the power and convenience of functions
Every function will have a set
of parentheses marking the
beginning and end of the arguments
Arguments
An argument is a value that the
function is excepting. The argument can be of any variable type.
There
are also occasions when a function will take no arguments at all,
like in phpinfo( ). Example time(), which returns the
current Unix timestamp.
Return
values
It is the value the function returns.
Functions can return value of any datatype:
arrays, integers, doubles (floating-point numbers), objects, or sometimes
Boolean values.
Important
PHP 4 Functions
In this section , we will break
down PHP 4 functions into logical groupings . We will also cover every
function used in the applications presented in all the chapters .
MySQL
API
Out of 33 MySQL functions
available , only 17 of these are used in the applications in the chapters
.
FREQUENTLY
USED MYSQL FUNCTIONS
MYSQL_CONNECT( )
You can't
do anything with MYSQL until you make the connection using the
following function ,
int mysql_connect(str
host, str username, str password)
MYSQL_PCONNECT(
)
The mysql_pconnect( ) function works exactly as mysql_connect( ) but
with one difference . The link to MySQL will not close when the
script finishes running .
int mysql_pconnect (str host, str username , str password )
MYSQL_SELECT_DB(
)
It changes the focus to the database you wish to query.
int
mysql_select_db (string database_name [, int link_identifier] )
MYSQL_QUERY(
)
mysql_query() sends a query to the currently active database on the
server that's associated with the specified link identifier.
resource mysql_query ( string query [, resource link_identifier [, int
result_mode]])
MYSQL_FETCH_ARRAY(
)
Once you have retrieved your result from a query , you will use this
function to retrieve the rows from a query.
array mysql_fetch_array ( resource result [, int result_type])
MYSQL_FETCH_ROW(
)
It works exactly as mysql_fetch_array() but it only returns a
numeric array of the fetched row.
array mysql_fetch_row ( resource result)
MYSQL_INSERT_ID(
)
Frequently the primary key of a MySQL table will be an auto_increment
field. This function returns the value of the auto_increment field
associated with the specific copy of the script .
int mysql_insert_id ( [resource link_identifier])
MYSQL_NUM_ROWS(
)
It tells you exactly how many rows have been returned by a select query.
int mysql_num_rows ( resource result)
MYSQL_AFFECTED_ROWS(
)
It returns the number of rows in a table that are affected by an update,
insert or delete query.
int mysql_affected_rows ( [resource link_identifier])
MYSQL_ERRNO(
)
If there is a problem with a query , this function will split out the
error number registered with MySQL .
int mysql_errno ( [resource link_identifier])
MYSQL_ERROR(
)
This function should accompany every mysql_query( ) you run .
string mysql_error ( [resource link_identifier])
MYSQL_RESULT(
)
This function grabs the contents of a specific cell.
mixed mysql_result ( resource result, int row [, mixed field])
LESS
FREQUENTLY USED MYSQL FUNCTIONS
MYSQL_FETCH_OBJECT(
)
This function provides another way to access data retrieved from a
query . object mysql_fetch_object ( resource result)
MYSQL_FREE_RESULT(
)
This function frees result memory used by a query .
bool mysql_free_result ( resource result)
MYSQL_CLOSE(
)
This closes the link to MySQL .
bool mysql_close ( [resource link_identifier])
MYSQL_DATA_SEEK(
)
This function repositions the cursor to the row number you specify ;
the first row is 0 .
bool mysql_data_seek ( resource result_identifier, int row_number)
MYSQL_CREATE_DB(
)
mysql_create_db() attempts to create a new database on the
server associated with the specified link
identifier.
bool mysql_create_db ( string database name [, resource
link_identifier])
MYSQL_DROP_DB(
)
It removes a database from MySQL .
bool mysql_drop_db ( string database_name [, resource link_identifier])
MYSQL_LIST_DBS(
)
It lists databases available on a MySQL server.
resource mysql_list_dbs ( [resource link_identifier])
MYSQL_LIST_TABLES(
)
If given a database name this function will return a result identifier
to a list of tables within a database .
resource mysql_list_tables ( string database [, resource
link_identifier])
MYSQL_LIST_FIELDS(
)
This function returns a result identifier .
resource mysql_list_fields ( string database_name, string table_name
[, resource link_identifier])
String
- handling functions
In creating Web-based
applicaitons , string handling and manipulation is one of the most
critical tasks of the language you work with . PHP's built - in String
handling functions covers most anything you'd want to do to text .
STRIP_TAGS(
)
This function removes HTML and PHP tags .
string strip_tags ( string str [, string allowable_tags])
ADDSLASHES(
)
This function is intended to work with your database insert
and update queries .
string addslashes ( string str)
STRIPSLASHES(
)
This function will remove the slashes inserted by the magic_quotes_gpc
or addslashes( ) .
string stripslashes ( string str)
STR_REPLACE(
)
This function replaces all occurences of the first argument
and replaces them with the string in the second argument .
mixed str_replace ( mixed search, mixed replace, mixed subject)
SUBSTR_REPLACE(
)
substr_replace() replaces a copy of string
delimited by the start and (optionally) length
parameters with the string given in replacement.
The result is returned.
string substr_replace (string string,string replacement, int start [,
int length])
STRCMP(
)
This function compares two strings .int strcmp ( string str1, string
str2)
STRLEN(
)
This function returns an integer that gives the number of characters
in a string. int strlen ( string str)
STRPOS(
)
This function returns the position of the string in the
second argument within the first argument.
int strpos ( string haystack, string needle [, int offset])
STRRPOS(
)
This function is similar to strpos( ) except that it finds the
final position of characters in the second argument .
int strrpos ( string haystack, char needle)
SUBSTR(
)
This function returns a portion of a string based on
numeric offsets .
string substr ( string string, int start [, int length])
STRREV(
)
This function reverses the order of a string .
string strrev ( string string )
STRTOLOWER(
)
This function makes an entire string lower case .
string strtolower ( string str)
STRTR(
)
This function takes the string in the first argument and translates
each character in the second argument to the corresponding character
in the third argument.
string strtr ( string str, string from, string to)
UCFIRST(
)
This function makes the first character in the string upper case.
string ucfirst ( string str)
UCWORDS(
)
This function makes the first character in every word in the string
upper case. string ucwords ( string str)
TRIM(
)
This function removes any white space from the begining and
end of a string including return characters , line feeds , spaces and
tabs .
string trim ( string str [, string charlist])
HTMLSPECIALCHARS(
)
This functions transforms < , > , & , and "
into their proper HTML entities : < , > , & ,
and " .
string htmlspecialchars ( string string [, int quote_style [, string
charset]])
GET_HTML_TRANSLATION_TABLE(
)
This function gets a full l ist of
characters that have HTML entities , or
just those used by htmlspecialchars( ) .
string get_html_translation_table ( int table [, int quote_style])
NUMBER_FORMAT( )
This
function formats a number to your specifications .
string number_format ( float number [, int decimals [, string
dec_point [, string thousands_sep]]])
NL2BR(
)
This function adds an HTML break (<br>) after each
newline (\n) in a string. string nl2br ( string string)
STRTOUPPER(
)
This function makes an entire string upper case .
string strtoupper ( string string)
MD5(
)
md5( ) is a one - way algorithm that encrypts information .
string md5 ( string str)
Regular
expression functions
EREG( )
Tests whether a
string matches a regular expression.
int ereg ( string pattern, string string [, array regs])
EREGI( )
This function is a
case-sensitive version of ereg( ) .
int eregi ( string pattern, string string [, array regs])
EREG_REPLACE( )
You can use
this function for string replacement based on complex string patterns
.
string ereg_replace ( string pattern, string replacement, string
string)
EREGI_REPLACE( )
This is
the same as ereg_replace( ) , except that the match is case-sensitive
. string eregi_replace ( string pattern, string replacement, string
string)
SQL_REGCASE(
)
This function
will alter strings so that you can use them in case-insensitive
regular expressions .
string sql_regcase ( string string)
PERL
- COMPATIBLE REGULAR EXPRESSIONS ( PCRE
)
The syntax for patterns used in
these functions closely resembles Perl. The expression should be enclosed
in the delimiters, a forward slash (/), for example. Any character can be
used for delimiter as long as it's not alphanumeric or backslash (\). If
the delimiter character has to be used in the expression itself, it needs
to be escaped by backslash. Since PHP 4.0.4, you can also use Perl-style
(), {}, [], and <> matching delimiters.
PREG_MATCH( )
Searches subject for a match to the
regular expression given in pattern.
preg_match() returns the number of times pattern
matches. That will be either 0 times (no match) or 1 time because
preg_match() will stop searching after the first match.
int preg_match ( string pattern, string subject [, array
matches])
PREG_REPLACE(
)
Perform a regular expression search and replace
.
mixed preg_replace ( mixed pattern, mixed replacement, mixed subject
[, int limit])
There are few PCRE function not
given here . But they can come handy to you in writing codes for your program.
They are : preg_match_all( ) , preg_quote( ) and preg_grep( ).
Type -
conversion functions
EXPLODE( )
This function
transforms a string into an array.
array explode ( string separator, string string [, int limit])
IMPLODE( )
This function
turns an array into a string .
string implode ( string glue, array pieces)
SPLIT( )
This function is
same as explode() , but it allows you to specify a regular expression
as the separation string .
array split ( string pattern, string string [, int limit])
PREG_SPLIT( )
This function
works like split() , only it uses a Perl regular expression as the
pattern .
array preg_split ( string pattern, string subject [, int limit [, int
flags]])
You can make use of spliti( ) ,
which uses a case-sensitive pattern match .
Array
functions
These functions allow you to interact with and manipulate arrays in
various ways. Arrays are essential for storing, managing, and operating on
sets of variables.
Simple and multi-dimensional arrays are supported, and may be either
user created or created by another function. There are specific database
handling functions for populating arrays from database queries, and
several functions return arrays.
ARRAY_FLIP( ) array_flip()
returns an array in flip order, i.e. keys from trans
become values and
trans's
values become
keys.
array array_flip ( array trans)
ARRAY_MERGE( )
array_merge()
merges the elements of two or more arrays together so that the values
of one are appended to the end of the previous
one.
array array_merge
( array array1, array array2 [, array ...])
ARRAY_SPLICE(
)
Remove a
portion of the array and replace it with something else
. array
array_splice(array input,int offset[,int length[,array replacement]])
COUNT(
)
Count elements in
a variable
.
int count ( mixed var)
ARRAY_COUNT _VALUES(
)
array_count_values()
returns an array using the values of the input
array as keys and their frequency in input
as
values.
array array_count_values ( array
input)
ARRAY_DIFF( )
array_diff()
returns an array containing all the values of array1
that are not present in any of the other arguments. Note that keys are
preserved.
array array_diff ( array array1,
array array2 [, array ...])
ARRAY_INTERSECT( ) array_intersect()
returns an array containing all the values of array1
that are present in all the arguments. Note that keys are preserved.
array array_intersect ( array array1, array
array2 [, array ...])
ARRAY_POP( )
array_pop()
pops and returns the last value of the array,
shortening the array by one element.
If array is empty (or is not an
array), NULL will be returned.
mixed array_pop
( array array)
ARRAY_PUSH( ) array_push()
treats array as a stack, and pushes
the passed variables onto the end of array.
The length of array increases by the
number of variables pushed .
int array_push
( array array, mixed var [, mixed ...])
ARRAY_RAND(
) array_rand()
is rather useful when you want to pick one or more random entries out
of an array. It takes an input array
and an optional argument num_req
which specifies how many entries you want to pick - if not specified,
it defaults to 1.
mixed array_rand ( array
input [, int num_req])
SHUFFLE( )
This function
shuffles (randomizes the order of the elements in) an array.
void shuffle
( array array)
IN_ARRAY( )
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.
bool in_array ( mixed needle, array haystack
[, bool strict])
SORT(
)
This function sorts an array. Elements will be arranged from
lowest to highest when this function has completed.
void sort
( array array [, int sort_flags])
Print
functions
PRINT(
)
This function
prints what you specify.
print ( string arg)
ECHO(
)
Output one or more
strings .
echo ( string arg1 [, string argn...])
PRINTF( )
Produces output
according to format .
void printf
( string format [, mixed args])
PRINT_R(
)
Prints
human-readable information about a variable .
void print_r
( mixed expression)
VAR_DUMP( )
This function
returns structured information about one or more expressions that
includes its type and value. Arrays are explored recursively with
values indented to show structure.
void var_dump
( mixed expression [, mixed expression [, ...]])
Date/time functions
DATE( )
Returns a
string formatted according to the given format string using the
given integer timestamp or the
current local time if no timestamp is
given.
string date
( string format [, int timestamp])
MKTIME( )
This
function is most useful for calculation valid
dates.
int mktime
( int hour, int minute, int second, int month, int day, int year
[, int is_dst])
TIME( )
This function
returns current time measured in number of seconds since the Unix
Epoch ( January 1 1970 00:00:00 GMT) .
int time(void)
MICROTIME( )
Return current UNIX timestamp with microseconds .
string microtime
( void)
Filesystem
functions
PHP has a whole range of
functions that enable you to manipulate files and directories on host
computer . Some of the important ones are shown below ,
FOPEN( )
Opens file or
URL .
int fopen ( string filename,
string mode [, int use_include_path])
FCLOSE( )
Closes an
open file pointer .
bool fclose ( int fp)
FEOF( )
Returns TRUE
if the file pointer is at EOF or an error occurs; otherwise
returns FALSE.
int feof
( int fp)
FGETS( )
Returns a
string of up to length - 1 bytes read from the file pointed to by
fp. Reading ends when length - 1 bytes have been read, on a
newline (which is included in the return value), or on EOF
(whichever comes first).
string fgets (
int fp [, int length])
FILE( )
Reads entire
file into an array.
array file ( string
filename [, int use_include_path])
UMASK( )
umask()
sets PHP's umask to mask & 0777 and returns the old umask.
int umask ( int mask)
COPY( )
Makes a copy of
a file. Returns TRUE if the copy
succeeded, FALSE otherwise.
int copy
( string source, string dest)
TEMPNAM( )
Creates a
file with a unique filename in the specified
directory.
string tempnam
( string dir, string prefix)
DIRNAME( )
Given a
string containing a path to a file, this function will return the
name of the directory.
string dirname (
string path)
Random
number generator functions
MT_SRAND(
)
This function seeds your random number generator
.
void mt_srand (int seed)
MT_RAND(
)
This function returns a random number . You can specify a minimum
or a maximum value
.
int mt_rand ([int min [ , int max ]])
cURL
functions
cURL is a library that allows
for communication between servers using a variety of protocols . cURL can
be used for its ability to communicate with HTTPS . This is a secure
protocol used in the shopping cart to do credit card transactions.
Session
functions
Sessions are means of
maintaining state between pages. HTTP does not allow servers to
remember much of anything between requests for pages from a specific
user. Sessions allow the server to keep track of activities by a
single user .
HTTP header functions
There are two vital HTTP
functions as follows ,
HEADER( )
header() is used to send raw HTTP
headers. The optional replace
parameter indicates whether the header should replace a previous
similar header, or add a second header of the same type. By
default it will replace, but if you pass in FALSE
as the second argument you can force multiple headers of the same
type.
int header ( string string [, bool replace])
SETCOOKIE( )
setcookie() defines a cookie to be sent along with the
rest of the header information. Cookies must be sent before
any other headers are sent (this is a restriction of cookies, not
PHP). This requires you to place calls to this function before any
<html> or <head>
tags.
int setcookie ( string name [, string value [, int expire [,
string path [, string domain [, int secure]]]]])
HEADER_SENT( )
This function returns TRUE if
the HTTP headers have already been sent, FALSE
otherwise
.
bool headers_sent ( void)
Mail
function
MAIL(
)
mail() automatically mails the message specified in message
to the receiver specified in to.
Multiple recipients can be specified by putting a comma between each
address in to.
bool mail (string to,string subject, string message[,string
additional_headers])
URL
functions
There will be occasions when
you will need to encode or decode text. For that you will use the
functions below ,
URLENCODE(
)
This function will encode a string so that it's URL ready. Most
often you will use it to send variable information to another page
.
string urlencode(string)
URLDECODE(
)
This function uncodes the encoding process
.
string urldecode(string)
RAWURLENCODE(
)
Returns a string in which all non-alphanumeric
characters except hypen, underscore and period have been replaced
with a percent (%) sigh followed by two characters
.
string rawurlencode(string)
Output
buffering
Output buffering is the process
of writing the results of your script to a temporary buffer . Instead of
being sent out over the Web it will gather in a buffer, where you can
manipulate.