Cover  Copyright  Contents  Reference  Index  previous  next
Chapter 2. BASICS

3. SYNTAX SUMMARY

Contents:
3. SYNTAX SUMMARY
3.1 Page structure
3.1.1 PHP tags
3.1.2 Comments
3.2 Data types
3.2.1 Scalars
3.2.2 Compound
3.2.3 Special
3.2.4 Pseudo
3.3 Variables
3.3.1 Variable name
3.3.2 Arrays
3.3.3 Global variables
3.3.4 Superglobal arrays
3.3.5 Deprecated arrays
3.3.6 Static variables
3.3.7 Variable reference
3.4 Constants
3.4.1 The define function
3.4.2 The magic constants
3.5 Operations
3.5.1 Arithmetic operations
3.5.2 Logical operations
Comparisons
Combinations
3.5.3 Bit operations
3.5.4 Concatenation operation
3.5.5 Assignment operation
3.5.6 Increment / Decrement
3.5.7 Conditional operation
3.5.8 Operation precedences
3.6 Expressions
3.7 Control structures
3.7.1 The if control structure
3.7.2 The switch control structure
3.7.3 The while control structure
3.7.4 The do ... while control structure
3.7.5 The foreach control structure
3.7.6 The for control structure
3.7.7 The break statement
3.7.8 The continue statement
3.7.9 The return statement
3.7.10 Alternative syntaxes
3.8 Functions
3.8.1 Function definition
3.8.2 Argument passed by value or by reference
3.8.3 Argument default value
3.8.4 Returned value
The return statement
The list statement
3.8.5 Predefined functions
3.9 PHP core functions
3.9.1 String functions
Presentation
Comparison
Analysis
Search and replace
Transformation
HTML
3.9.2 Date and time functions
3.9.3 Array functions
Array creation
Array handling
Properties
Sorting
Set operations
Transformations
3.9.4 File system functions
Data access
File management
Environment management
Security
3.9.5 Variable functions
3.9.6 PHP options and informations
3.9.7 Miscellaneous functions
The eval function
Script execution control
Constant functions
Pack and unpack
3.10 Class and object
3.10.1 Class definition
Class definition
Class constructor
Class destructor
Class property
Class method
Class this
Static member
Constant member
Class file
Class autoload
3.10.2 Class extension
3.10.3 Objects
The eval function
Script execution control
Constant functions

 

3.1 Page structure

3.1.1 PHP tags

Preferred notation
<?php  . . . ?>
Short notation
<?  . . . ?>
ASP notation
<%  . . . %>
HTML notation
<SCRIPT language="php" >

     . . . 

</SCRIPT>

3.1.2 Comments

one-line
// comments to end-of-line
The double slashes introduces the comments

multi-line
/* start comments
   multi-line
last line */
The comments are enclosed within the /* and */ signs.

3.2 Data types

3.2.1 Scalars

The four scalar types are:
booleanboolean with value true of false (reserved words, case insensitive)

integerinteger -- size is platform dependent -- usually minimum: -2147483648 maximum: +2147483647.
Example: 12345

floata.k.a double, real number -- floating point number. Formats:
123.45
1.2345E+2
12345.e-2

stringcharacter string.

Quotes. Examples:
"This is a string"
'Here is another'
Single or double quotes:

-within double quotes, variables are expanded, i.e. replaced by their value before printing occurs
-within single quotes, variable names are string data
-single quotes within double quotes or double quotes within single quotes are data
Examples:
$var="abcd";
print ("This string: $var");- result: This string: abcd
print ('This string: $var');- result: This string: $var
print ("This string: '$var'");- result: This string: 'abcd'
print ('This string: "$var"');- result: This string: "$var"

The heredoc syntax:

<<<word

      multiple-line text

word
The triple <<< sign introduces the group
word is a user chosen word that starts and closes the multi-line text.
The ending word must stand alone in its line, excepting a semi-colon if it ends a statement
Example:
$text = <<<EOB
This text has multiple lines
The semi-colon ends the assignment statement
EOB is a user chosen word
EOB;

3.2.2 Compound

Two compound types - composed of scalar type components:
arraysee 3.3.2 below
objectsee 3.10 below

3.2.3 Special

Two special types:
resourcereturned by some functions, like mysql_connect (returns a connection resource)
nullthe only value is null (case insensitive)

3.2.4 Pseudo

Three pseudo-types are introduced by the reference manual, for presentation purpose:
mixeddata of any of several types
numberinteger or float type
callbacka function as used as an argument of functions like call_user_function or usort. Example:
$func = 'myfunction';
call_user_function ($func)

will call the function myfunction. $func has the callback type here.

3.3 Variables

3.3.1 Variable name

The name of a variable of any type has the following structure:
$variable_name
where:
$$ sign to appear as is
variable_namethe variable name, has the following structure:
size:unlimited number of characters
case:case sensitive
first character:alphabetic or underscore
the rest:alphabetic, numeric or ASCII code 127 to 255 (x'8F' to x'FF')

3.3.2 Arrays

Creation

Creating the array itemwise

$array_name [key] = value
where the charaters in blue are to be coded "as is"; the variable values are:
array_namename of the array; created if it did not exist
keyidentification of a key, an integer or a string, enclosed within quotes if a string
valuevalue of the key, of any data type, enclosed within quotes if a string
The key can be omitted (array_name[]=value); when omitted, it defaults to the next unassigned integer

Creating the whole array

$array_name = array ("key" => value, ...)
where the charaters in blue are to be coded "as is"; the variable values are:
array_namename of the array being created
keyidentification of a key, an integer or a string, enclosed within quotes if a string
valuevalue of the key, of any data type, enclosed within quotes if a string
The key and its accompanying sign => can be omitted. The implicit key is then numeric and has the first unassigned value (highest assigned value plus 1)

Examples:

$address = array("lastName" => "Adams", "firstName"=>"Fanny", "email"=>"fadams@hata.us")
$myArray = array ("a" => 10, 7 => "abc", "x", 12)
In the $myArray array:
$myArray[8] has the value "x"
$myArray[9] has the value 12

Item identification

To identify an array item:
$array_name [key]
where the charaters in blue are to be coded "as is"; the variable values are:
array_namename of the containing array
keyidentification of a key. This can be:
-an integer
-a string, enclosed within quotes
-omitted -- the key is then assumed to be numeric and has the next value not yet assigned in the script

3.3.3 Global variables

Global variables are variables accessible from anypoint of a script.

The user defines a global variable in one of these several ways:
- use the global keyword
- use the $GLOBALS array

Using the global keyword

global $x, $y, $z
This defines $x, $y and $z as global variables.

Using the $GLOBALS array

GLOBALS[var] = value
where:
varis the name given to the variable (without the $ sign -- the variable is referenced as $var.
valueis the value assigned to the variable

Global variables also come from other sources: these the superglobal arrays. Cf infra.

3.3.4 Superglobal arrays

From version 4.1.0 autoglobal a.k.a superglobal arrays are defined. The auto qualifier points to the fact that they are global without the need to be declared by a global keyword. The super qualifier points to the fact that they are global even inside functions.

The autoglobal arrays are:

Data destined to the script
$_GETdata from a form using the GET method
$_POSTdata from a form using the POST method
$_COOKIEdata from the cookie sent in with the current message
$_REQUESTdata found in $_GET, $_POST and $_COOKIE
$_FILESfile information received from a file uploading form using the POST method
Data found in the surrounding system
$_SERVERdata from the server (includes HTTP header data from the request message)
$_ENVdata from the environment in which the PHP parser is running
Program data
$_SESSIONdata from the session under which the script is running
$GLOBALSdata put there to be accessible from anywhere in a script (note there is no underscore in the name)

$_GET and $_POST

The keys in these arrays are the names of the elements in the originating FORM.

$_COOKIE

The keys in this array are the names of the cookies and the values, the values of the cookies.

$_REQUEST

This array contains all of the items contained in the $_GET, $_POST and $_COOKIE arrays

$_FILES

This array contains the informations on uploaded files:
-each key is the name (name attribute) of an INPUT element (with type"file" attribute) that caused the uploading
-the associated value is an array that contains the definition of the corresponding uploaded file The contents of such an array are:
KeysValues
nameis the original name of the uploaded file
typeis the data type of the uploaded file (e.g. 'text/thml')
tmp_nameis the absolute path of the temporary file where the data are uploaded
erroris the error level of the upload operation
sizeis the uploaded file size

$_SERVER

This array contains informations held in the server. These are:
-identification informations on the PHP server
-informations on the script currently execution
-HTTP headers of the request message
-identfication informations on the requesting client (these are in the HTTP headers)
The complete description of these informations, along with their keys is to be found in the reference manual.
Accompanying this book is a script (PHP_SERVER.php) which displays the values of its $_SERVER array. If you have set up your Web Server as suggested, you can submit this script by clicking here

$_ENV

This array contains informations imported from the operating system in which PHP is running. The complete description of these informations, along with their keys is to be found in the reference manual.
Please click here to see the a simple script you can run to display these informations for your system. The code strictly needed is in red. This script is available in the samples directory under the name 'PHP$_ENV.php'. If you have set up your Web Server as suggested, you can submit the script by clicking here

$_SESSION

This array contains informations on the current session. A simple script you can run is available in the samples directory under the name 'PHP$_SESSION.php'. To see significative results, you have to run it from a script which has defined session variables.

$GLOBALS

This array contains the globally accessible data put there by the user's scripts.

3.3.5 Deprecated arrays

The superglobal arrays described in the above deprecate and are to be used preferrably to the old style so-called long arrays HTTP_*_VARS, where the * sign stands for GET, POST, COOKIE, REQUEST, FILES, SERVER, ENV, SESSION: $HTTP_GET_VARS, $HTTP_POST_VARS, etc...

From version 5.0.0 onward, the long arrays HTTP_*_VARS may be disabled.

3.3.6 Static variables

Declaration:
static var_name = initial_value
where:
var_nameis the name of the variable to declare
initial_valueis the initial value of the variable
This is a declaration, i.e. the variable is not reset to the initial value each time the line is encountered in the program flow.

3.3.7 Variable reference

$bar = &$foo
Modifying $bar also modiifes $foo

3.4 Constants

3.4.1 The define function

A constant is defined by a define function. Syntax:
define ("constant_name", "constant_value", case_insensitive)
where:
constant_nameis the name of the constant to declare -- no $ sign precedes the name
constant_valueis the initial value of the constant
Only a scalar value (integer, float, string, boolean) is valid
case_insensitiveis a boolean value specifying whether the constant name is case insensitive (true) or not (false) -- default: false (the constant is case sensitive)

3.4.2 The magic constants

Some of the "magic constants" are (the _ is doubled before and after the letters):
__FILE__absolute path of the file where the "constant" is used
__LINE__number of the line where the "constant" is used
__FUNCTION__name of the function where the "constant" is used -- undefined if outside of any function
__CLASS__name of the class where the "constant" is used -- undefined if outside of any class
__METHOD__name of the method where the "constant" is used -- undefined if outside of any method
It may be noted that these data are not really constants since they vary according to their location within a script.

3.5 Operations

3.5.1 Arithmetic operations

CodeSignificationExample - with $a=15 $b=7
+Addition$a + $b result: 22
-Subtraction$a - $b result: 8
*Multiplication$a * $b result: 105
/Division$a / $b result: 2.142857142857...
%Modulus$a % $b result: 1

3.5.2 Logical operations

Comparisons

CodeSignificationExample - with $a=15 $b=7
<Less than$a < $b result: false
<=Less than or equal$b <= $a result: true
==Equal$a == $b result: false
===Identical$a === $b result: false
!=Not equal$a != $b result: true
<>Not equal$a <> $b result: true
!==Not identical$a !== $b result: true
>=Greater than or equal$a >= $b result: true
>Greater than$a > $b result: true

Combinations

CodeSignificationExample - with $a=15 $b=7 $c=0
||OR$a || $b result: true
orOR$a or $b result: true
xorExclusive OR$a xor $b result: false
andAND$a AND $b result: true
&&AND$a && $c result: false
!NOT!$a result: false
The codes using letters are case-insensitive (you can write 'xor', 'XOR', 'Xor', etc...)
Reference

3.5.3 Bit operations

CodeSignification - Examples: $a and $b have the bit configurations 11110000 and 01010101
&bitwise AND - bits are combined with results as follows:
0 & 0 = 0
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1
Example: $a & $b has the bit configuration 01010000
|bitwise OR - bits are combined with results as follows:
0 | 0 = 0
0 | 1 = 1
1 | 0 = 1
1 | 1 = 1
Example: $a | $b has the bit configuration 11110101
^bitwise exclusive OR - bits are combined with results as follows:
0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0
Example: $a ^ $b has the bit configuration 10100101
~unary operation - 0 is transformed to 1, and vice versa
Example: ~$b has the bit configuration 10101010
<<Shift left -- shift the bits in the first operand a number of times to the left as defined by the second operand
Example: $b << 3 has the bit configuration 10101000
>>Shift right -- shift the bits in the first operand a number of times to the right as defined by the second operand
Example: $a >> 3 has the bit configuration 00011110
Reference

3.5.4 Concatenation operation

CodeSignification
.concatenation Example: "abc"."defg" the result is "abcdefg"

3.5.5 Assignment operation

Simple assignment

$a = $b The value of $b is copied into $a

Shorthands

$a += $bstands for $a = $a + $b
$a -= $bstands for $a = $a - $b
$a *= $bstands for $a = $a * $b
$a /= $bstands for $a = $a / $b
$a %= $bstands for $a = $a % $b
$a .= $bstands for $a = $a . $b
$a &= $bstands for $a = $a & $b
$a |= $bstands for $a = $a | $b
$a ^= $bstands for $a = $a ^ $b
$a <<= $bstands for $a = $a << $b
$a >>= $bstands for $a = $a >> $b

3.5.6 Increment / Decrement

$a++$a is incremented by 1, after performing the operation where $a is involved, if any
++$a$a is incremented by 1, before performing the operation where $a is involved, if any
$a--$a is decremented by 1, after performing the operation where $a is involved, if any
--$a$a is decremented by 1, before performing the operation where $a is involved, if any

3.5.7 Conditional operation

Syntax:
(condition) ? $x : $y
If the condition is true, the value of the expression is $x; else, it is $y. Example:
$min = ($a < $b) ? $a : $b

3.5.8 Operation precedence

Please click here to see the table giving all of the operators ordered by decreasing precedence.

3.6 Expressions

The PHP reference manual defines an expression as anything that has a value.

As a construct, an expression is a number of constants, variables or functions linked by operators such as presented in the above. The simplest of expressions are single constant or variables: 5, $a

Some of the expression unwonted for the newcomer to PHP are:

ExpressionUnwonted use
$a = $b $c = ($a = $b)
$c = $a = $b
$a < $b ($a < $b) * $c
$a < $b is a logical expression that can be used for its numeric value (0 when false, 1 when true)

An expression, by nature, has one of the types as defined in the above
Any expression has a value in any of the scalar types.

3.7 Control structures

3.7.1 The if control structure

The complete syntax:
if (condition) {
  if_statements
}
elseif (condition_1) {
  elseif_statements_1
}

   . . .

else {
  else_statements
}
where:
conditionis a logical expression, or an expression of any type tested for its boolean value
if_statementsis the set of statements executed if condition is true
condition_1is a logical expression, or an expression of any type tested for its boolean value
elseif_statements_1is the set of statements executed if condition is false and condition_1 is true.
. . .stands for other elseif clauses -- each of these come into play only if all the conditions previously stated are false
else_statementsis the set of statements executed if all of the conditions are false
All of the elseif and else clauses are optional.

3.7.2 The switch control structure

switch ($var) {

   case const_1: 

     statements_1

   case const_2:

     statements_2

   ...

}
where:
$varis the switching variable
const_1is a constant expression
statements_1is the set of statements executed if the switching variable is equal to the constant const_1
const_2is a constant expression
statements_2is the set of statements executed if the switching variable is equal to the constant const_2
...stands for more case clauses
The execution of a switch statement is as follows:
- the switch variable $var is compared to the successive constant expressions specified in the case clause; as soon as a match is found, the execution starts with the first statement in the clause, and stops at a break statement; this can carry to successive case clauses, and to the end of the statement if no break statement is encountered.

3.7.3 The while control structure

while (condition) {

   loop_statements

}
where:
conditionis a logical expression or an expression of another type used for its boolean value -- tested before each loop
loop_statementsis the set of statements executed if condition is true
As long as the condition is true, the loop_statements are executed again and again.

3.7.4 The do ... while control structure

do {

   loop_statements

} while (condition);
where:
loop_statementsis the set of statements executed at each loop
conditionis a a logical expression or an expression of another type used for its boolean value -- tested at the end of each loop; if true, a new loop is run.
As long as the condition is true, the loop_statements are executed again and again.

3.7.5 The foreach control structure

foreach (array as $value) {

  statements to process $value

}
foreach (array as $key => $value) {

  statements to process $key and $value

}
where:
arrayis an expression the value of which is an array
$valueis a value extracted from the array as defined by the array expression
$keyis a key extracted from the array as defined by the array expression (the second form extracts a key and its related value)
statementsis the set of statements executed for each of the extracted value (and key in the second form) -- at the start of a foreach statement, the position in the array is reset to the first value (so there is no need to reset it explicitly). The $value variable (and the $key variable in the second form) are available for processing in the statement set

See also each statement of the array functions set.

3.7.6 The for control structure

for (initial_set; condition; end_loop_set) {

        loop_body_statements

}
where:
initial_setis the set of comma separated statements executed before the beginning of the first loop
conditionis a a logical expression or an expression of another type used for its boolean value -- tested before each loop; if true, the new loop is run.
end_loop_setis the set of comma separated statements executed at the end of each loop
loop_body_statementsrepresents the set of statements (ending with semi-colons) executed if the condition is true

3.7.7 The break statement

break
 
Used in a switch, while, do, for or foreach statement set -- terminates the statement

3.7.8 The continue statement

continue
 
Used in a while, do, for or foreach statement set -- terminates the current loop, and schedules the next

3.7.9 The return statement

return value
where:
valueis an expression the value of which is to be returned
This statement is used in a function. It terminates the execution of the function and has the latter return the value as defined by the value expression.

3.7.10 Alternative syntaxes

Alternative syntaxes exist for the control structures: if, elseif, else, while, for, foreach, switch. In these syntaxes:
- the opening curly brace is replaced by a colon (:)
- the ending curly brace by the endxxx word:

The if control structure

if (condition): 
   if_statements
elseif (condition):
   elseif_statements
...
else:
   else_statements
endif;

The while control structure

while (condition):
   statements
endwhile;

The for control structure

for (intial_set; condition; ;end_loop_set):
   loop_statements
endfor;

The foreach control structure

foreach (array as $value):
  statements to process $value
endforeach;
foreach (array as $key => $value):
  statements to process $key and $value
endforeach;

The switch control structure

switch ($var):
   case const_1: 
     statements_1
   case const_2:
     statements_2
   ...
endswitch;

3.8 Functions

3.8.1 Function definition

function func_name (argument_list)
Function defined independently of any condition and other function - may be referenced from anywhere in the script
if (condition) {
   ...
   function func_name (argument_list);
   ...
} //end if structure
The function is defined only after its definition is encountered in the execution flow
function containing_function (arguments) {
   ...
   function func_name (argument_list)
   ...
}
The function is defined only after the containing function is executed
The argument list can be omitted (the parentheses are still required). This is a comma separated list of variables and/or variable references.

3.8.2 Argument passed by value or by reference

In the function definition, an argument can be:
- either the plain name of a variable
- or the name of a variable preceded by an ampersand (&)
When a plain variable name, the variable is passed by value: modifications to the variable in the function are not reflected to the original variable.
When a variable name preceded by an ampersand, the variable is passed by reference: the function directly operates on the original variable, so that any change to the variable within the function is reflected on the original variable.

3.8.3 Argument default value

In the function definition, an argument can be assigned a value. This is the argument default value, i.e. the value the argument would take on if the argument is omitted in the function call.

3.8.4 Returned value

The return statement

The value returned by a function is specified by the return statement:
return value
where value is the value returned by the function.

The list statement

The list statement can be used to retrieve the items of a returned array into different variables.
function multi_return ( ... ) {
  ...
  $arr = ($x, $y, $z);
  ...
  return $arr
}
...

list ($a, $b, $c) = multi_return ( ... );
The variables $a, $b, $c will receive the values of $x, $y, $z, respectively.

3.8.5 Predefined functions

PHP offers a number of predefined functions which are available from the PHP system core. These are described under the Function reference heading in the reference manual, where they are mixed with functions provided by extension modules.

Some of the functions from the PHP core are presented below

3.9 PHP core functions

Presented in the following are some of the:
- string functions
- date and time functions
- array functions
- file system functions
- variable functions
- PHP options and informations functions
- miscellaneous functions

3.9.1 String functions

An exhaustive description if the PHP string functions is to be found in the reference manual. Some of the most usual of these are presented in the following.

A string function processes a string passed as an argument to it. The original string is not changed by the function. When it is said, in the following presentation, that such and such operation is performed on the string, this means that the operations are performed on a copy of it, in order to obtain a resulting string which is returned by the fonction. The origninal string is unaltered.

Presentation
bin2hexreturns the hexadecimal representation of a string
chrreturns a character of a given ASCII code
echooutputs one or more strings
fprintfwrites out a string in a given format, to a specified stream
money_formatreturns a number formatted into a currency representation
number_formatreturns a formatted float number
ordreturns the ASCII code of the first character in a string
printwrites out a string
setlocalesets the environment to use the presentation standard of a given country (in terms of currency, date and time, etc.)
printfwrites out a set of strings according to a given format
sprintftransforms a set of strings using a format, and returns the resulting string
vprintfprints out the contents of an array as a string presented according to a given format
vsprintfreturns the contents of an array as a string presented according to a given format
 
Search & replace
str_replacereplaces all occurrences of a given search string (str_ireplace is the case-insensitive version)
strpbrkreturns the string starting at first occurrence of a character from a given set
strposreturns the position of the first occurrence of a search sequence in a string (stripos: case-insensitive)
strrchrreturns the portion of a string starting with the last occurrence of a search sequence
strrposreturns the position of the last occurrence of a search sequence (strripos: case insensitive)
strstrreturns the portion of a string starting with the first occurrence of a search sequence (stristr: case insensitive)
strtokreturns the next token as delimited by any character of a given set
substrreturns a substring defined by its offset and length
substr_replacereplaces the text within a portion of a string
 
Analysis
explodesplits a string into the substrings delimited by a separator, and returns them in an array
parse_strretrieves the parameter names and values from a URL like string
str_splitcuts a string into chunks of a given length and returns the result into an array
str_word_countcounts the words in a string and returns either their number or the words themselves in an array
strcspnlength of the maximum segment at the beginning of a string, free of any of the characters of a given set
strlenreturns the length of a string
substr_countreturns the number of occurrences of a text sequence within a string
 
Construction
implodeputs together the substrings contained in an array, joining them by a given character
 
Comparison
strcmpstring comparison (strcasecmp: case-insensitive)
strnatcmpstring comparison using the 'natural order' (strnatcasecmp: case-insensitive)
strncmpcomparing the first n characters of two strings (strncasecmp: case-insensitive)
substr_comparecompares substrings from two strings
 
Transformation
addslashesAdd backslashes to escape quotes (single and double) and backslashes -- see also stripslashes
str_padpads a string on the left, the right or both sides with a given padding string
str_repeatrepeats a string a number of times
stripslashesremove the escape backslashes (see: addslashes)
strrevreverse the character order in a string
strtolowerconverts all characters to lower case
strtoupperconverts all characters to upper case
strtrtransliterates characters in a string
trimremoves white space from both ends of a string (ltrim removes from the left end, rtrim from the right end)
ucfirstconverts the first character of the string to upper case
ucwordconverts the first character of each word to upper case
 
HTML
htmlentitiesreplaces the characters undesirable in an HTML code by their entity representation
html_entity_decodeconverts entity representations in a string into the characters they represent
nl2brinserts <br> line break tags before new line characters, in a string
striptagsremoves the <br> tags from a string

Please refer to the reference manual for more.

Presentation

bin2hex

bin2hex (string)
where:
stringis the string to process
Returns the hexadecimal representation of the processed string
Reference

chr

chr (ascii)
where:
asciiis the ASCII code of a character - in decimal numeration
Returns the character of the given ASCII code
Reference

echo

echo (string, string, ...)
where:
stringis a string to write out
Outputs one or more strings Reference

fprintf

fprintf (handle, format, list)
where:
handleidentifies the destination stream -- default: the standard output
formatis the format to be used
listis the list of the data to be printed out
writes out the string in the given format, to the stream specified by the handle.

A format is composed of a number of elements, each of which has the following components:

0.%the percent sign -- to appear as is
1.right-padding specifier(optional)
. 0
. 'x -- (x prefixed by a single quote) the single quote to appear as is, pad with the 'x' character
. default: pad with space characters
2.alignment specifier(optional)
. - (dash) left justify
. default: right justify
3.width specifier(optional) minimum number of characters in the formatted element
4.precision specifier(optional) ignored if argument not a float -- number of digits after the decimal point
5.type specifierone of the following:
% - no argument required
b - argument used as an integer -- presented as a binary number
c - argument used as an integer -- presented as the character having the argument as its ASCII code
d - argument used as an integer -- presented as a signed decimal number
u - argument used as an integer -- presented as an unsigned decimal number
f - argument used as a float -- presented as a floating point number
o - argument used as an integer -- presented as an octal number
s - argument used as a string -- presented as string
x - argument used as an integer -- presented in hexadecimal format, using lower case letters
X - argument used as an integer -- presented in hexadecimal format, using upper case letters
Examples (note that in the explanations, format is interpreted from right to left):
%0-10ddecimal number (d) with a minimum of 10 characters (10), left justified (-), padded with '0' (0)
%'*12ddecimal number (d) with a minimum of 12 characters (12), right justified (by default), padded with '*' ('*)
%-15sstring occupying 15 character positions, left justified, padded with spaces

The format is made of format elements put together, without intervening spaces. Example - 2 format elements: %0-10d%'*12d

Each element in the data list is displayed using the format element of the same rank in the format. If the data list has more elements than the format, the latter is wrapped around.

Complete example:
fprintf(%0-10d%'*12d, $a, $b, $c)

-$a is printed with the format element %0-10d
-$b is printed with the format element %'*12d
-$c is printed with the format element %0-10d
Reference

money_format

money_format (format, number)
where:
formathas the following contents:
0.%the percent sign, to appear as is
1.flagsoptional -- zero, one or more allowed, each flag is one or two characters as follows:
=f - where 'f' is a fill character -- default: space
^ disable use of character grouping
+ + and - signs used
( if negative, number is within ( and ), no - sign used
! suppress currency symbol
- left-justify -- default: right-justify
2.widthminimum number of characters in the field (default: 0)
3.left precision# sign, followed by minimum number of characters to the left of the decimal character (e.g. decimal point)
4.right precision. sign, followed by number of characters to the right of the decimal character -- default: value as customary in the currency's country
5.conversionpossible values are:
inumber formatted according to international format for the locale's currency
('locale' is set by the setlocale function: setlocale(LC_MONETARY,locale), with some of these values:
setlocale(LC_MONETARY,en_US) for the USA,
setlocale(LC_MONETARY,fr_FR) for France,
setlocale(LC_MONETARY,de_DE) for Germany, etc.)
nnumber formatted according to the currency's country format
%returns the % character
numberis the number to display
Returns the number in the currency representation as defined by the format
Reference

number_format

number_format (float, decimals, dec_point, thousand_sep)
where:
floatis the float number to display
decimalsoptional -- is the number of decimal digits
If omitted:
- number represented without decimal digits
- thousand groups (groups of 3 digits) separated by commas
- the subsequent arguments must be omitted
dec_pointcharacter used as the decimal point -- default: . dot
thousand_sepcharacter used to separate groups of 3 digits
Returns the float number in the specified format.
Reference

ord

ord (string)
where:
stringthe string to be processed
Returns the ASCII code (in the decimal numeration system) of the first character in the string
Reference

print

print (string)
where:
stringis the string to write out
The parentheses may be omitted.
Writes out the specified string.
Reference

printf

printf (format, data_list)
where:
formatis the format to use to represent the data in the data list. The format is as described in connection with the fprintf function above.
data_listis the comma separated list of data to print
Writes out the specified strings according to the given format.
Reference

setlocale

setlocale (category, locale, ...)
setlocale (category, array)
where:
categoryis the information category for which the locale is set. Possible categories are:
LC_ALLsets locale for all of the below
LC_COLLATEsets locale for string comparisons
LC_CTYPEsets locale for character ordering
LC_MONETARYsets locale for money representation
LC_NUMERICsets locale for number formatting
LC_TIMEsets locale for time and date formatting
localeidentifies a country.Example:
en_USfor the USA
en_UKfor the United Kingdom
de_DEfor Germany
fr_FRfor France
it_ITfor Italy
jp_JPfor Japan
etc..
arrayis an array that contains a list of locales
Sets the programming environment to use the standards of the designated country as the default representation of the specified category of numbers.
Reference

sprintf

sprintf (format, data_list)
where:
formatis the format to use. The format is as described in connection with the fprintf function.
data_listis the comma separated list of data to be converted
Returns the specified string presented in the specified format.
Reference

vprintf

vprintf (format, array)
where:
formatis the format to use to represent the data in the data list. The format is as described in connection with the fprintf function above.
arrayis the array to print out
Prints out the items of the specified array, as a string presented according to the specified format.
Reference

vprintf

vsprintf (format, array)
where:
formatis the format to use to represent the data in the data list. The format is as described in connection with the fprintf function above.
arrayis the array to format into a string
Returns the items of the specified array, in a string presented according to the specified format.
Reference

Search and replace

str_replace

str_replace (search, replace, subject, &count)
where:
searchstring to be looked for, or array each item of which is to be looked for -- a string can be considered an one element array
replacestring to replace, or array each item of which is to replace the item of the same rank in the search array -- if there are less items in the replace array than in the search array, extra items in the search array are replaced by the empty string -- a string can be considered an one element array.
subjecta string or an array to be processed -- when an array each item is processed independently
&countoptional -- a count variable passed by reference, to receive the count of replacements completed
Replaces the occurrences of the search strings as defined by the search argument by the corresponding replace strings as defined by the replace argument, and returns the result -- the subject string is not modified.
str_ireplace is the case-insensitive version of the function
Reference.

strcspn

strcspn (string, cspn, start, length)
where:
stringis the string to process
cspnis a tring containing the tested characters
startoptional -- is the offset in the string from which to process; if omitted, the processing starts at the beginning of the string
lengthoptional -- is the length to process; if omitted, process to the end of the string
Returns the length of the maximum segment from the beginning of the processed string, free of any of the characters of the cspn set
Reference.

strpbrk

strpbrk (string, charlist)
where:
stringis the string to process
charlistis the string that contains the characters to be searched for
Returns the string starting at the first occurrence of any character from the charlist set -- false if none of the characters in the set is found.
Reference.

strpos

strpos (string, search, offset)
where:
stringis the string to be searched
searchis the string to be searched for
offsetoptional -- is the position in the searched string from which to search
Returns the position of the first occurrence of the search sequence in a string -- boolean false if not found
stripos: case-insensitive search
Reference.

strrchr

strrchr (string, search)
where:
stringis the string to process
searchis a string, the first or only character of which is to search for
Returns the portion of the string starting with the last occurrence of the character as specified by the char argument, and going to the end of the processed string -- false if the character is not found.
Reference.

strrpos

strrpos (string, search, offset)
where:
stringis the string to process
searchis the sequence to search for
offsetoptional -- is the offset of the position where the search is to start -- if omitted, search starts at the beginning of the string
Returns the position of the last occurrence of a search sequence -- false if the search string is not found.
strripos: case insensitive search
Reference.

strstr

strstr (string, search)
where:
stringis the string to be searched
searchis the string to be searched for
Returns the portion of the searched string starting with the first occurrence of the search sequence as specified by the search argument -- false if the search string is not found.
stristr: case insensitive search
Reference.

strtok

strtok (string, tokset)
where:
stringstring is the string to process
toksetis a string any character of which delimits a token in the process string
Returns the next token as delimited by any character of the specified tokset set -- false after the end of the string is reached. To return successive token from the , the strtok is to be used repeatedly, without the string argument. Example:
$token = strtok($string, ' \n\r\t');
while ($token){
  //process $token ....
  $token = strtok(' \n\r\t');
}//end while
This sequence processes the tokens delimited by a space, a new line, a carriage return or a tab character. Reference.

substr

substr (string, offset, len)
where:
stringis the string to process
offsetis the offset of the substring to return, in the processed string (character at offset included in the result)
lenoptional -- is the length of the substring to return -- if omitted, the substring to be returned extends to the end of the string.
Returns the substring as defined by its offset and length in the processed string -- substring ($s,0) returns the entire string $s.
Special offset values:
-offset negative - the offset is from the end of the string (offset=-1 identifies the last character, -2 the last but 1, etc); the substring from this offset to the end is returned
-offset beyond last character (>= string length), false is returned
Reference.

substr_replace

substr_replace(string, replace, offset, len)
where:
stringis the string to process
replaceis the replacement text
offsetis the offset of the sequence to be replaced
lenoptional -- is the length of the sequence to be replaced -- if omittted, it is the same as that of the replace sequence
Replaces the sequence defined by its offset and length, with the replace sequence, and returns the result (the original string is not modified).
Reference.

Analysis

explode

explode (separator, string, limit)
where:
separatoris a string (not a character)
stringis the string to explode
limitoptional -- is the limit number of exploded elements
Splits a string into the substrings as delimited by the separator, and returns them in an array. If the limit argument is present, the number of elements into which the string is split is limited to that limit, with the last element possibly containing one or more occurrences of the separator.
Reference

parse_str

parse_str (string, array)
where:
stringis the URL like string to parse for names and values
arrayoptional -- if present, the results are put in the array, with keys being the names and values being the values
In an URL parameters consist of name and value pairs:
- each name and value pair has the form name=value
- name-and-value pairs are separated by the & sign: name=value&name=value& ...
The function retrieves the parameter names and values from the string. If the array argument is present, each name and value pair is put in the array as a key and a value. If the array argument is omitted, each name and value pair is used to create a variable in the current scope, with name and value given by the pair.
Reference

str_split

str_split (string, len)
where:
stringis the string to cut up
lenoptional -- length of the chunks into which the string is to be cut up. Default: 1 (the string is cut up into single characters)
Cuts up the string into chunks of the given length and returns the array containing the chunks.
Reference.

str_word_count

str_word_count (string, format)
where:
stringis the string to process
formatoptional -- is an integer that defines how the word count is to be carried out - possible values are:
1the words are returned in an array
2the words are returned in an associative array where:
- the key is the position of a word in the string (first position: 0)
- the associated value is the corresponding word
If omitted, the function returns the number of words
Returns the number of words, or the words themselves in an array, as requested by the formt.
Reference.

strlen

strlen (string)
where:
stringis the string the length of which is queried
Returns the number of characters contained in the string passed as argument.
Reference.

substr_count

substr_count (string, substr)
where:
stringis the string to be searched
substris the string to be looked for
Returns the number of occurrences of the substr sequence within the specified string
Reference.

Construction

implode

implode (glue, array)
where:
glueis the character string to be used to link the imploded elements together
arrayis the array the items of which are glued together, linked by the glue element
Puts together the substrings contained as items in the specified array, joining them by the glue string, and returns the result (the original array is unmodified)
.
Reference

Comparison

strcmp

strcmp (string_1, string_2)
where:
string_1first string
string_2second string
The strings string_1 and string_2 are compared bitwise. The result is:
0if the strings are equal
< 0if string_1 is less than string_2
> 0if string_1 is greater
strcasecmp is the case-insensitive version of the function.
Reference

strnatcmp

strnatcmp (string_1, string_2)
where the strings string_1 and string_2 are compared using the 'natural order'. The result is:
0if the strings are equal
< 0if string_1 is less than string_2
> 0if string_1 is greater
strnatcasecmp is the case-insensitive version of the function.
Reference

strncmp

strncmp (string_1, string_2, n)
where:
string_1is the first string
string_2is the second string
nis the number of characters to compare
The first n characters of strings string_1 and string_2 are compared. The result is:
0if the strings are equal
< 0if string_1 is less than string_2
> 0if string_1 is greater
strncasecmp is the case-insensitive version of the function
Reference

substr_compare

substr_compare (string_1, string_2, offset, len, case)
where:
string_1is the first string
string_2is the second string
offsetis the offset of the substrings to compare
lenis the number of characters to compare -- if omitted, the substrings to compare extend to the end of their respective strings
case
optional:true the comparison is case insensitive
false the comparison is sensitive (this is the default)
The substrings starting at the specified offset, with the specified length from string_1 and string_2 are compared. The result is:
0if the strings are equal
< 0if string_1 is less than string_2
> 0if string_1 is greater
Reference

Transformation

addslashes

addslashes (string)
where:
stringis the string to process
Add backslashes to escape quotes (single and double) and backslashes found in the processed string, and returns the result (the original string is unmodified) -- see also stripslashes
Reference.

str_pad

str_pad (string, len, pad, mode)
where:
stringis the string to process
lenis the length of the resulting string
padoptional -- is the string to use for padding - default: space
modeoptional -- possible values:
STR_PAD_RIGHTpad on the right (this is the default)
STR_PAD_LEFTpad on the left
STR_PAD_BOTHpad equally on both side
Pads a string on the left, the right or both sides with a given padding string, and returns the result (the original string is unmodified)
Reference.

str_repeat

str_repeat (string, number)
where:
stringis the string to repeat
numberis the number of times to repeat
Returns a string composed of the given string repeated the number of times as specified by the number argument Reference.

stripslashes

stripslashes (string)
where:
stringis the string to process
Remove the escape backslashes before the quote (single or double) and backslash sign, and returns the result (the original string is unmodified)
(see also: addslashes) Reference.

strrev

strrev (string)
where:
stringis the string to process
Returns the string with characters in reversed order
Reference.

strtolower

strtolower (string)
where:
stringis the string to process
Converts all the characters in the string to lower case, and returns the result (the original string is unmodified)

Reference.

strtoupper

strtoupper (string)
where:
stringis the string to process
Converts all the characters in the string to upper case, and returns the result (the original string is unmodified)

Reference.

strtr

strtr (string, source, target)
strtr (string, array)
where:
stringis the original string to process
sourceis the string that contains the characters to translate
targetis the string that contains the translated characters: each character of the original string encountered in the source string is replaced by the character of the same rank in the target string. If the source string is longer, any character that finds no match in the target string is ignored.
arrayis the array that defines the transliteration thus: a substring from the original string is used as a key to access the array, if found, it is replaced by the value associated with the key. The longest match is sought for. The replacement sequences are not acted upon anew.
Returns the string translated as described (the original string is unmodified)
. Reference.

trim

trim (string, charlist)
where:
stringis the string to process
charlistoptional -- is the string made of the characters to remove from both ends of the string
If omitted, to be removed are the white-space characters which are the following:
" "ASCII x"20" - space
"\n"ASCII x"0A" - new line
"\r"ASCII x'0D" - carriage return
"\t"ASCII x'09" - tab
"\0"ASCII x'00" - nul byte
"\x0B"ASCII x'0B' - vertical tab
Removes the characters contained in the charlist string from both ends of the processed string, and returns the result (the original string is unmodified)

ltrim removes the characters from the left end,
rtrim removes the characters from the right end
Reference.

ucfirst

ucfirst (string)
where:
stringis the string to process
Converts the first character of the string to upper case, and returns the result (the original string is unmodified)

Reference.

ucword

ucword (string)
where:
stringis the string to process
Converts the first character of each word in the string to upper case, and returns the result (the original string is unmodified)
Reference.

HTML

htmlentities

htmlentities (string, which_quote, charset)
where:
stringis the string to be converted
which_quoteoptional -- convert single or double quote:
ENT_COMPAT -- convert double quotes, leave single quotes alone
ENT_QUOTES -- convert both single and double quotes
ENT_NOQUOTES -- leave both double and single quotes alone
Defaut: convert double quotes, leave single quotes alone
charsetoptional -- character set to be used -- default: ISO-8859-1
For more, see the reference manual
replaces the characters undesirable in an HTML code (&, <, > etc...) by their entity representation (&amp;, &lt;, &gt;, etc...) and returns the result (the original string is unmodified)
Reference.

html_entity_decode

html_entity_decode(string, which_quote, charset)
where:
stringis the string to be converted
which_quoteoptional -- convert single or double quote:
ENT_COMPAT -- convert double quote entities, leave single quote entities alone
ENT_QUOTES -- convert both single and double quote entities
ENT_NOQUOTES -- leave both double and single quote entities alone
Defaut: convert double quote entities, leave single quote entities alone
charsetoptional -- character set to be used -- default: ISO-8859-1
For more, see the reference manual
Converts entity representations (&amp;, &lt;, &gt;, &quot;, etc.) in the string into the characters they represent, and returns the result (the original string is unmodified)
Reference.

nl2br

nl2br (string)
where:
stringis the string to process
Inserts <br> line break tags before new line characters, in the process string, and returns the result (the original string is unmodified).
Reference.

striptags

striptags ()
where:
stringis the string to be processed
Removes the <br> tags from the processed string, and returns the result (the original string is unmodified)
Reference.

3.9.2 Date and time functions

The date and time functions are:
checkdatechecks the validity of a Gregorian date given as month, day and year numbers
datereturns the date and time in a specified format, for the current time or a given timestamp
getdatereturns the date and time elements in an associative array, for the current time or a given timestamp
gettimeofdayreturns the current time of the day as elapsed seconds since Jan 1st, 1970, and microseconds in the second
gmdatereturns GMT date and time in a specified format, for the current time or a given timestamp,
gmmktimereturns the timestamp for a GMT date and time given in numeric presentation
gmstrftimereturns a formatted string representation of GMT date and time for the current time or a specified timestamp
idatereturns one chosen element of date and time (hour, day, etc.) for the current time or a specified timestamp
localtimereturns elements of the local time, in an array
microtimereturns the current time in seconds and microseconds
mktimereturns the timestamp for a local date and time specified in integer representation
strftimereturns the date and time in a specified format, for the current local time, or a given local timestamp
strtotimeconverts a string description of date and time in English, into a timestamp
timereturns the current Unix timestamp (number of seconds elapsed since Jan 1st, 1970, 00h 00mn 00s)

checkdate

checkdate (month, day, year)
where:
monthan integer month number
dayan integer day number
yearan integer year number
Returns true if the month, day and year represent a valid Gregorian date, false otherwise. Reference.

date

date (info, timestamp)
where:
infoa combination of letters that indicates the information to be displayed. Example:
Y F d-G:i:s indicates that the returned information is composed of the year full 4-digit (Y), the month name in full (F), the day of the month with leading 0 (d), the hour in 24-hour format (tt>G). Thus:
2004 November 09-23:47:02
The available letters are shown in the following table - characters not in the table are returned "as is":
aLower case am and pm timeam or pm
AUpper case AM and PM timeAM or PM
BSwatch Internet time000 through 999
cISO 8601 date2004-11-26T23:15:12+01.00
dday of the month, with leading 001 to 31
Dday of the week in 3 lettersMon through Sun
Fmonth in fullJanuary through December
g12-hour format without leading 01 through 12
G24-hour format without leading 01 though 24
h12-hour format with leading 001 through 12
H24-hour format with leading 001 through 24
iminutes with leading 000 through 59
I(capital i) daylight saving time1: yes, 0: no
jday of the month without leading 01 through 31
l(lowercase L) day of the week in fullMonday through Sunday
Lleap year indication1: yes, 0: no
mmonth numeric representation with leading 001 to 12
Mmonth name abbreviation, in 3 lettersJan through Dec
nmonth numeric representation without leading 01 to 12
Odifference to GMT+0300
rRFC2822 formattedFri, 26 Nov 2004 00:23:12 +0100
sseconds with leading 000 through 59
SEnglish ordinal suffix for day of the monthst, nd, rd, th
tnumber of days in month28 through 31
Ttimezone settingEST,
UUNIX timestamp2959200
wnumber of the day in the week0 for Sunday through 6 for Saturday
WISO 8601 week number in the year(week starts on Monday)
y2-digit representation of year04
Y4-digit representation of year2004
zday of the year0 through 365
Ztimezone offset in seconds+3600
timestampopitional -- is a Unix timestamp, i.e. the number of seconds elapsed since January 1st, 1970 -- if omitted, is equal to the current Unix timestamp as returned by the time function.
Returns the formatted time as defined by the info argument.
Reference.

getdate

getdate (timestamp)
where:
timestampoptional -- is the Unix timestamp, i.e. the number of seconds elapsed since January 1st, 1970 -- defaults to the current timestamp
Returns the date and time corresponding to the specified timestamp, in an associative array. The keys in this associative array, and the values they are associated with are:
"seconds"Number representation of seconds0 through 59
"minutes"Number representation of minutes0 through 59
"hours"Number representation of hours0 through 23
"mday"Number representation of day of the month1 through 31
"wday"Number representation of day of the week0 (Sunday) through 6 (saturday)
"mon"Number representation of the month1 through 12
"year"Full number of the year1970 through 2038
"yday"Number representation of the day of the year0 through 365
"weekday"Day of the week in fullSunday through Saturday
"month"Month name in fullJanuary through December
0Unix timestampNumber of seconds elapsed since the Unix Epoch (January 1st, 1970 - 00h 00mn 00s)
Reference.

gettimeofday

gettimeofday ( )
with no argument.
Returns the time of the day informations in an associative array with the following keys:
"usec"microseconds in the second
"sec"seconds in the minute
"minuteswest" minutes west of Greenwich in the day
"dsttime"daylight-saving-time time indicator (1: yes)
Reference.

gmdate

gmdate (info, timestamp)
where:
infois a combination of letters that indicates the informations to return
timestampoptional -- Unix timestamp, if omitted, defaults to the current time
This function is identical to the date function except that it returns the GMT time
Reference.

gmmktime

gmmktime (hour, minute, second, month, day, year, dsttime)
where:
hourNumber representation of the hour in the day
minuteNumber representation of the minutes in the hour
secondNumber representation of the seconds in the minute
monthNumber representation of the month
dayNumber representation of the day of the mont
yearNumber representation of the year
dsttimeDaylight saving time indication
Returns the Unix timestamp corresponding to the GMT date and time specified by the arguments
All arguments are optional. When one is omitted, all those to its right must be omitted.
Any omitted argument defaults to its current GMT value
Reference.

gmstrftime

gmstrftime (info, timestamp)
where:
infois a combination of time information elements that indicates which are returned in the result
timestampopional -- Unix timestamp -- defaults to the current time stamp
The function is identical to strftime below, except it returns the elements of GMT time.
Reference.

idate

idate (info, timestamp)
where:
infois one character that identifies the information to return. The recognized characters are:
BSwatch Internet time000 through 999
dday of the month, with leading 001 to 31
h12-hour format with leading 001 through 12
H24-hour format with leading 001 through 24
iminutes with leading 000 through 59
I(capital i) daylight saving time1: yes, 0: no
Lleap year indication1: yes, 0: no
mmonth numeric representation with leading 001 to 31
sseconds with leading 000 through 59
tnumber of days in month28 through 31
UUNIX timestamp2959200
wnumber of the day in the week0 for Sunday through 6 for Saturday
WISO 8601 week number in the year(week starts on Monday)
y2-digit representation of year04
Y4-digit representation of year2004
zday of the year0 through 365
Ztimezone offset in seconds+3600
timestampoptional -- is the timestamp an related value of which is to display -- when omitted, defaults to the current Unix timestamp
Returns the informations from the timestamp as requested by the info argument.
Reference.

localtime

localtime (timestamp, is_associative)
where:
timestampoptional -- is the timestamp to process -- if omitted, defaults to the current timestamp as returned by the time function.
is_associativeoptional -- is a boolean expression -- when true causes the result to be returned as an associative array; when false or omitted, the result is returned as a numerically indexed array
The associative array has the following keys and values:
"tm_sec"seconds of the minute
"tm_min"minutes of the hour
"tm_hour"hour of the day
"tm_mday"day of the month
"tm_mon"month of the year, starting at 0
"tm_year"years since 1900
"tm_wday"day of the week
"tm_yday"day of the year
"tm_isdst"daylight saving time indicator (0: in effect, 1: not in effect)
Returns the local timestamp informations into an array, as specified by the is_associative argument.
Reference.

microtime

microtime (return_float)
where:
return_floatoptional -- is a boolean expression which, when true causes the function to return the results in floating point format; when false or omitted, the function returns the results integer formats
The function returns a string that contains the current Unix timestamp in seconds and microseconds, in the format:
msec sec
where msec is the number of microseconds, and sec is the timestamp in seconds.
Your operating system must support the gettimeofday system call.
Reference.

mktime

mktime (hour, minute, second, month, day, year, isdst)
where:
houroptional -- is an integer representing the hour
minuteoptional -- is an integer representing the minute
secondoptional -- is an integer representing the second
monthoptional -- is an integer representing the month
dayoptional -- is an integer representing the day
yearoptional -- is an integer representing the year
isdstoptional -- is an integer indicating whether day light savings time is in effect (value 1) or not (value 0), or to be determined by PHP (value -1)
The function returns the Unix timestamp corresponding to the date and time specified by the arguments
All of the arguments are optional. When an argument is omitted, all arguments to its right must be omitted also. An omitted argument defaults to its current local date and time value.
Reference.

strftime

strftime (info, timestamp)
where:
infoinformation list composed of a combination in any desired order of elements selected from the list below:
%aday of the week abbreviated name in the current locale format
%Aday of the week full name in the current locale format
%bmonth abbreviated name in the current locale format
%Bmonth full name in the current locale format
%cdate and time in preferred format for current locale
%Ccentury number
%dday of the month with leading 001 to 31
%Dmonth/day/year equivalant to the %m/%d/%y combination
%eday of the month, space padded to the left" 1" to "31"
%g2-digit number of the year to which the week pertains, as determined by %V (cf. infra)
%G4-digit number of the year to which the week pertains, as determined by %V (cf. infra)
%hsame as %b
%Htime in 24-hour format with leading 000 through 23
%I(capital i) time in 12-hour format with leading 001 to 12
%jday of the year with leading 0001 to 366
%mmonth number with leading 001 to 12
%Mminutes00 to 59
%nnew line character
%pam or pm time qualification, or corresponding strings in the current locale format
%ra.m. or p.m. time qualification
%Rtime in 24-hour notation
%Sseconds in number representation
%ttab character
%Tcurrent time in the form hh:mn:ss -- equivalent to %H:%M:%S
%uday of the week in number representation1: Monday to 7:Saturday
%Uweek of the year in number representationweek starts on Sunday -- first week starts on first Sunday
%Vweek of the current year in ISO 8601:1988 representation 01 to 53weeks start on Monday -- week 01 is the first that has 4 days or more
%Wweek of the current year number weeks starts on Monday -- week 01 starts on first monday of the year
%wday of the week -- Sunday is day 0
%xdate without time, in current locale preferred format
%Xtime without date, in current locale preferred format
%yyear in 2-digit format00 through 99
%Yyear in 4-digit formatEx: 2004
%Ztime zone, full name or abbreviation
%%a % litteral character a
timestampoptional -- Unix timestamp -- if omitted, defaults to the current local timestamp
Returns the local time elements as requested by the info argument
Reference.

strtotime

strtotime (string)
where:
stringis a string containing a verbal description of time in English
The function returns:
-the Unix timestamp corresponding to the description. This description is supposed
.relative to a timestamp previously set by a strtotime("timestamp") function
.relative to the current time, if no strtotime("timestamp") was executed
-the value -1 if the parsing fails
Reference.

time

time ()
Returns the current Unix timestamp, i.e. the number of seconds elapsed since January 1, 1970, 00h 00mn 00s, as an integer.
Reference.

3.9.3 Array functions

The most usual of the PHP array functions are presented in the following. For a more complete presentation in the reference manual, please click here. Besides, arrays can be created, or otherwise handled using appropriate notations, as discussed elsewhere.
 
Array creation
arraycreates an array
array_combinecreates an associative with items from one array as keys, from another as values
array_fillfills a range of numeric keys with a given values
array_mergemerges two or more arrays
array_merge_recursivemerges two or more arrays recursively, i.e. matching arrays found in the first level arrays are also recursively merged
compactcreates an associative array from a list of variables with the variable names as keys
rangereturns an array containing the elements of a certain ordered set comprised in a specified range
 
Array handling
array_popremoves an item from the end of an array and returns its value
array_pushadds one or more items to the end of an array
array_reduceapplies iteratively a function to the values of an array and returns the value so obtained
array_searchsearches an array for a given value, and returns the corresponding key
array_shiftremoves an item from the beginning of an array and returns its value
array_sumreturns the sum of the values in an array
array_unshiftadds one or more items to the beginning of an array
currentreturns the current element in an array
eachreturns the current key and associated value and advances the pointer to the next item
endsets the pointer to the last item
extractcreates the variables with the keys from the array as names and their values as values
keyreturns the current key
listassigns a list of values to a list of variables
nextreturns the value at the next position and moves the array internal pointer forward
prevreturns the value at the previous position and moves the array internal pointer backward
resetresets the pointer to the first element
 
Properties
array_count_valuesreturns the number of occurrences of each value found in an array
array_key_existsreturns true if a given key is found in the array
array_keysreturns the keys found in an array
array_valuesreturns all the values of an array
countcounts the elements in an array
in_arraytests if a given value is a value contained in the array
 
Sorting
asortsorts an associative array on its values, and maintain index association -- arsort sorts in reverse order
ksortsorts an array by keys -- krsort sorts in reverse order
natsortsorts an array using the natural order -- natcasesort case insensitive
sortsorts an array by values and reassigns them numeric keys -- rsort sorts in reverse order
uasortsorts an associative array by value using a user-defines comparison function, maintaining key/value association
uksortsorts an array by key using a user-defined comparison function
usortsorts an array by value using a user-defined comparison function
 
Set operations
array_chunksplits an array into smaller arrays with a given number of items
array_diff_assoccompares values with the same key in two array and returns the key/value pairs where difference is found
array_diffreturns all key/value pairs of an array that are not found in any of a set of other arrays
array_intersec_assocreturns the key/value pairs of an array found in all of the other arrays from a given set
array_intersectreturns the key/value pairs of an array where the value is found in all of the other arrays from a given set
 
Transformations
array_filterfilters the items of an array, using a callback function
array_flipswitches keys and values in an array
array_mapderives a new value from each value, using a callback function and returns the key/pair values with the new values
array_reversereturns an array with items in reverse order
array_sliceextracts a slice from an array
array_spliceremoves a portion of an array and replaces it
array_uniquereturns an array with all duplicates key/value pairs removed
array_walkapplies a user function to every item of an array and returns the array so transformed
array_walk_recursiveapplies a user function to avery item of an array, recursively (i.e. when an item is an array, an array_walk recursive is applied to it), and returns the array so transformed

Array creation

array - creates an array

array (key/value, ...)
where:
key/valueis a key/value pair coded in either of the forms:
key=>valuewith an explicit numeric or string key -- key and value within quotes if a string
valuewith only a value -- within quotes if a string
When the key is omitted:
-it is implicitly numeric
-it takes on the next value not assigned by the arguments on the left
Example:
$a = array(5 =>"fadams@hata.com","name"=>"Fanny","surname" => "Adams", 123,"London")
The value '123' has the numeric key of '6', "London" has the numeric key of '7'

The function creates an array with the items as defined by the arguments.
Reference

array_combine - combines the values of an array with those of another to form key/value pairs

array_combine (keys, values)
where:
keyis the array the keys are taken from
valueis the array the values are taken from

Creates an associative array with values from the keys array as keys, from the values array as values: each key common to the key and value arrays gives a key/value pair in the result array, with the key in the pair being the value from the keys array, and the value, the value from the values array.
This result is returned. The arrays used as arguments are unchanged.
Reference

array_fill

array_fill (start, number, value)
where:
startis the numeric starting index
numberis the number of items
valueis the value to fill in

The function creates an array filled with the specified value, starting with the specified start index, and extending over the specified number of items, and returns this array.
Reference

array_merge

array_merge (array_1, array_2, ...)
where:
array_1is the first array to be merged
array_2is the second array to be merged
...stands for possible other arrays

The function merges two or more arrays.
Keys are treated as follows:

-each string key is added once to the result array; as the source arrays are examined in the order of the argument list, each new value encountered for a key overrides the previous one
-values associated with numeric keys are all added to the result array and reassigned numeric keys in sequential order, with values from the first array assigned first, then values from the second array, etc.

This result is returned. The arrays used as arguments are unchanged. Reference

array_merge_recursive

array_merge_recursive (array_1, array_2, ...)
where:
array_1is the first array to be merged
array_2is the second array to be merged
...stands for possible other arrays

The function recursively merges two or more arrays. This means that when a string key is encountered more than once, instead of having the most recent value overriding the previous ones, all of the values are set into an array which is retained as a value of the resulting array, with the common key as the associated key.

This result is returned. The arrays used as arguments are unchanged. Reference

compact

compact ($varname, . . .)
where:
$varnameis the name of a variable, or a variable that contains the name of a variable, or an array that contains the names of multiple variables
-if an argument is the character string which constitutes a variable name, it must be enclosed within quotes (single or double), with no $ sign
-if an argument is a scalar or an array variable which contains the names, this variable is to be passed with its $ sign
. . .stands for further variable names
The function creates an associative array from the list of variable names with these names as keys and the variable values as values.
This result is returned. The arrays used as arguments are unchanged.

Example:

$a = 1;
$b = "xyz";
$c = "tuv";
$d = 2;
$x = "b";
$arr = ('c', "d");
$res = compact("a", $x, $arr);
$res is the array: $res = ($a=>1, $b=>"xyz", $c=>"tuv", $d=>2)
Reference

range

range (low, high, step)
where:
lowis the lower limit of the range
highis the higher limit of the range
stepis the number of rank increment from one element to the next

The function returns an array containing the values comprised in a range from a known ordered set such as integers, lower case or upper case letters, etc. Example:
range (100, 200, 20) is the array containing: 100, 120, 140, 160, 180, 200
Reference

Array handling

array_pop

array_pop (array)
where:
arrayis the array to process

The function removes the item from the end of the processed array and returns its value part. The array passed as argument is changed. See also array_push, array_shift, array_unshift.
Reference

array_push

array_push (array, data_list)
where:
arrayis the array to process
data_listis a comma separated list of data item to push on to the array. The data can be constants or variables, or anything that can be put into an array (e.g. another array)

The function adds data items contained in the list to the end of the array. The array passed as argument is changed. The new number of items in the array is returned. See also array_pop,array_shift, array_unshift.
Reference

array_reduce

array_reduce (array, callback)
where:
arrayis the array to process
callbackis the function to be applied

The function applies iteratively the callback function to the values of the array and returns the final value so obtained. The array passed as argument is unchanged.
Reference

array_search

array_search (search, array, strict)
where:
valueis the data to search for
arrayis the array to search
strictoptional -- if true, a match occurs only if the data agree in value and in type
The function searches the array for the specified value, and returns the corresponding key, if found, or the value false otherwise. If there are more than one match, the key corresponding to the first occurrence is returned.
Reference

array_shift

array_shift (array)
where:
arrayis the array to process
The function removes an item from the beginning of an array and returns its value part. The remaining items in the array is shifted one position to the left. The array passed as argument is changed. See also array_unshift, array_pop, array_push.
Reference

array_sum

array_sum (array, , )
where:
arrayis the array to process

The function returns the sum of the values in the array, used as numbers. The array is unchanged.
Reference

array_unshift

array_unshift (array), data, . . .)
where:
arrayis the array to process
datais a datum to be added at the beginning of the array
. . .stands for possible further data to be added at the beginning of the array

The function adds one or more items to the beginning of an array, and returns the new number of items in the array. The array passed as argument is changed. See also array_shift, array_pop, array_push.
Reference

current

current (array)
where:
arrayis the array to process

The function returns the value of the current item in the array (an array has an internal pointer that identifies its 'current' item -- this pointer is initially set to identify the first item in the array, and can be modified by certain operations on the array).
Reference

each

each (array)
where:
arrayis the array to process

The function returns the current key and associated value, and advances the array internal pointer to the next item.
Each key and value pair is returned as a 4-item array with:
- keys 0 and 'key' having as value the item key name
- keys 1 and 'value' having as value the item value
Reference

end

end (array)
where:
arrayis the array to process

The function sets the internal pointer to the last item of the array and returns this item's value.
Reference

extract

extract (array, mode, prefix)
where:
arrayis the array to process
modeoptional -- is the extraction mode which defines how special situations are to be handled
prefixoptional -- is a character string that can be used as the prefix of the created variable names

The function creates variables accessible to the script, with the keys from the array as their names and the corresponding values from the array as their values. The mode argument defines how exception conditions are to be handled. The possible values of the argument are:

EXTR_OVERWRITE - if a key has the same name as an existing variable, its value overwrites the old value of the existing variable
EXTR_SKIP - if a key has the same name as an existing variable, it is skipped, leaving the existing value untouched
EXTR_PREFIX_SAME - if a key has the same name as an existing variable, the new variable is created with this name and the specified prefix added
EXTR_PREFIX_ALL - prefix all variables to be created, with the specified prefix
EXTR_IF_EXISTS - do not create new variables, only change the values of existing variables to the values of the keys with the same name
EXTR_PREFIX_IF_EXISTS - create a new variable for each key that has the same name as an existing variable, with the prefix added to the created name
EXTR_REFS - the created variables reference the value in the processed array, so that changing these variables also changes the corresponding values in the array
When omitted, the mode defaults to EXTR_OVERWRITE.

The keys must have names valid for variables. Numeric keys will raise an exception condition.
Reference

key

key (array)
where:
arrayis the array to process

The function the returns the key at the current position identified by the internal pointer.
Reference

list

The list function is used in a notation like this:
list (variable_list) = array_expression
where:
variable_listis the comma separated list of the variables to be assigned values
array_expressionis an expression the value of which is an array

The variables named in the variable_list are assigned the values of the array expression coded on the right handside of the equal sign. Each variable is assigned the value of the item of the same rank in the array. By omitting a variable at a given rank in the list (using 2 consecutive commas), an item from the array can be skipped.
Reference

next

next (array)
where:
arrayis the array to process

The functions advances the internal pointer of the array to the next position, and returns the value at the new position, or false is there is no more value. A false value is also returned if the value to be returned is NULL
Reference

prev

prev (array)
where:
arrayis the array to process

The function moves back the array internal pointer one position, and returns the value at the new position, of false if the pointer was at the beginning of the array. A false value is also returned if the value to be returned is NULL
Reference

reset

reset (array)
where:
arrayis the array to process

The function resets the internal pointer to the first item in the array, and returns the value of that item.
Reference

Properties

array_count_values

array_count_values (array)
where:
arrayis the array to process

The function returns in an array the number of occurrences of each value found in the processed array
Reference

array_key_exists

array_key_exists (key, array)
where:
keyis the key (an integer or a string) to be searched for
arrayis the array to search

The function returns true if the specified key is found in the array, ot false otherwise.
Reference

array_keys

array_keys (array, value)
where:
arrayis the array to process
valueoptional -- only the keys having the value are returned -- if omitted, all of the keys are returned

The function returns in an array the keys of the array:
- restricted to those with the specified value, if value is specified
- all of them if value is omitted
Reference

array_values

array_values (array)
where:
arrayis the array to process

The function returns in an array all the values of the array
Reference

count

count (array, mode)
where:
arrayis the array to be processed
modeoptional -- is the count mode which can be set to COUNT_RECURSIVE to cause the count to proceed recursively
The function returns the number of items contained in the array.

When counting recursively, if an item is an array, this array is counted recursively, and the result of this counting is added to the total count.
Otherwise, the function counts the items in the array, an item which is an array is counted for 1, without counting what it contains.
Reference

in_array

in_array (value, array, strict)
where:
valueis the value to search for
arrayis the array to search
strictoptional -- is a boolean expression which, when true also requires the equality of type for a match

The function returns true if the specified value is found in the array. If the strict argument is true, the specified value must also match the type in the array to be found equal.
Reference

Sorting

These functions sort an array passed as an argument, and as a result modify the array. They return the boolean value true on success, and false on failure.

asort

asort (array, flag)
where:
arrayis the associative array to sort
flagoptional -- requests a special mode of sorting. For the possible values see sort below.

The function sorts an associative array on its values, and retains the key associated to each value. The array passed as argument is transformed. The value true is returned is the sort is successful; false is returned otherwise.
Reference
Other similar functions are:
arsort sorts an associative array in reverse order

ksort

ksort (array, flag)
where:
arrayis the array to sort
flagoptional -- selects a special mode of sorting -- see the sort function below.

The function sorts the array by keys. The array passed as argument is transformed. The function returns true on success, false on failure.
Reference Other similar functions are:
krsort sort by keys in reverse order

sort

sort (array, flag)
where:
arrayis the array to sort
flagoptional -- is a flag that select a special mode of sorting. The possible values are:
SORT_REGULARvalues are compared normally -- this is the default
SORT_NUMERICvalues are compared for their numeric values
SORT_STRINGvalues are compared for their string value

The function sorts an array by values and reassigns them numeric keys -- any string keys are discarded. The array passed as argument is transformed. The function returns true on success, false on failure.
Reference
Other similar functions are:
rsort sorts by values in reverse order
natsort sorts by values using the "natural" order
natcasesort sorts by values using the "natural" order, disregarding case

uasort

uasort (array, function)
where:
arrayis the array to be sorted
functionis the name of the user-defined comparison function -- if the name is hard coded as a string, it is within "quotes" (as any string constant should be)
The function sorts the array by value using the user-defined comparison function, retaining the key associated to each value. The array passed as argument is transformed. The true value is returned if the sort is successful. Otherwise, the value false is returned

The user comparison function must admit two arguments and return:
 0 if the 2 arguments are equal
-1 if the first argument is less than the second
+1 if the first argument is the greater
Reference

uksort

uksort (array, function)
where:
arrayis the array to sort
functionis the name of the user-defined comparison function -- if the name is hard coded as a string, it is within "quotes" (as any string constant should be)

The function sorts the array by key using the user-defined comparison function. The array passed as argument is transformed. The true value is returned if the sort is successful. Otherwise, the value false is returned
Reference

usort

usort (array, function, )
where:
arrayis the array to sort
functionis the name of the user-defined comparison function -- if the name is hard coded as a string, it is within "quotes" (as any string constant should be)

The function sorts the array by values using the user-defined comparison function. The array passed as argument is transformed. The values are assigned numeric keys which reflect their ranks in the sorted array. The old keys are discarded
The true value is returned if the sort is successful. Otherwise, the value false is returned
Reference

Set operations

array_chunk

array_chunk (array, size, preserve_key)
where:
arrayis the array to process
sizeis the number of items in each resulting chunk
preserve_keyoptional -- is a boolean indicator with the following effect:
- when true: the keys from the original array are preserved
- when false or omitted: new numeric keys are used, starting with 0 in each resulting chunk

The function splits the given array into smaller arrays with the number of items as specified by size in each. The result is returned as an array containing the smaller arrays as its items. The array passed as argument is unchanged.
Reference

array_diff

array_diff (array, array_1, . . .)
where:
arrayis the array to process
array_1is an array to use in the difference
. . .stands for further arrays that my be used in the difference

The function returns an array containing all the key/value pairs from the array to process, where the value is not found in any of the other arrays (note that the keys are preserved).
Reference

array_diff_assoc

array_diff_assoc (array, array_1, . . .)
where:
arrayis the array to process
array_1is an array to use in the difference
. . .stands for further arrays that may be used in the difference

The function returns an array containing all the key/value pairs from the array to process, that are not found in any of the other arrays (note that the keys are preserved). The arrays passed as arguments are unchanged.
Reference

array_intersect

array_intersect (array, array_1, . . .)
where:
arrayis the array to process
array_1is an array to intersect the array to process
. . .stands for possible further arrays to intersect the array to process

The function returns the key/value pairs of the array to process, where the value is found in all of the other arrays (note that the original keys are preserved). The arrays passed as argument are unchanged.
Reference

array_intersect_assoc

array_intersect_assoc (array, array_1, . . .)
where:
arrayis the array to process
array_1is an array to intersect the array to process
. . .stands for possible further arrays to intersect the array to process

The function returns the key/value pairs of the array to process, which are found in all of the other arrays (note that the original keys are preserved). The arrays passed as arguments are unchanged.
Reference

Transformations

array_filter

array_filter (array, function)
where:
arrayis the array to process
functionis the name of the filtering function

The filtering function is automatically called for each of the items in the array, and gives the indication as to retain the item or filter it out. The filtering function must accept the item to be tested as an argument. It returns true if the item is to be retained, false if it is to be filtered out. The array_filter function returns the array that contains the key/value pairs, where the value is retained (note that the original keys are preserved). The array passed as argument is unchanged.
Reference

array_flip

array_flip (array)
where:
arrayis the original array, to process

The function returns the array where the keys are the values of the original array, and the associated values, the associated key. The array passed as argument is unchanged. These points are to be considered:

-keys must be valid in the resulting array, which means that a value in the original arrays must be either a string or a number
-each key in the resulting array must be unique -- if a value occurs more than once in the original array, the key it generates has as a value the last key associated with that value; the other keys are lost

Reference

array_map

array_map ('function', array, array_1, ...)
where:
functionis the name of the callback function to treat the items of the array to process -- the function name must be enclosed within quotes
arrayis the original array, to process
array_1optional -- parameter of the callback function
. . .stands for possible extra parameter arrays

The callback function is called to derive a new value from each value in the array to process. The array_map function returns the array containing the new key/pair values, with the keys unchanged from the original array and the values, the new values as changed by the callback function. The array passed as argument is unchanged.
Beside the value from the first array, the callback function can accept as an argument a value from one or more other arrays. The number of arrays in the argument list of array_map must be equal to the number of arguments of the callback function.
Reference

array_reverse

array_reverse (array, preserve_key)
where:
arrayis the array to process
preserveoptional -- is a boolean indicator
When true, it causes the original keys to be preserved

The function returns the specified array with items in reverse order. If the prserve argument is true, the original keys are preserved. The array passed as argument is unchanged.
Reference

array_slice

array_slice (array, offset, number)
where:
arrayis the original array, to process
offsetis the numeric index from which to take a slice
numberoptional -- is the number of items to include in the extracted slice; if omitted, the items to include go to the end of the array

The function returns the array made up of the specified number of items from the original array, starting from the specified offset. If the number is not specified, all the items from the starting index to the end of the original array are included in the result. The array passed as argument is unchanged.
Reference

array_splice

array_splice (array, offset, number, replacement)
where:
arrayis the original array to process
offsetis the numeric index from which the array items are to be removed
numberis the number of items to remove
replacementoptional -- is the replacement array to put in place of of the removed items

The function removes the specified number of items from the original array, starting at the specified offset, and replaces them by the specified replacement array:

-if the item number is omitted, the items to remove go up to the end of the original array
-if the replacement array is omitted, the removed items are not replaced
The array passed as argument is unchanged.
Reference

array_unique

array_unique (array)
where:
arrayis the original array, to process

The array_unique function first sorts the original array, on the values treated as strings. In the resulting array, the first key/value pair for each value is retained, the same value with the other keys are discarded. The final results so obtained is returned. The array passed as argument is unchanged.
Reference

array_walk

array_walk (array, callback, param)
where:
arrayis the original array to process
callbackis the user callback function which will be automatically scheduled to process each of the item of the original array, and return a value
paramoptional -- is a parameter that can be passed to the callback function
The callback function typically has 2 or 3 arguments as follows:
function ($value, $key, $param)
where the param argument is optional
For each of the key/value pair from the original array, the array_walk function calls the callback function passing it:
- the value in the pair as the first argument
- the key in the pair as second argument
- the param argument, if defined, ass the third argument
The value returned by the callback function is the value of the resulting key/value pair, where the key is the original key. The array_walk function return the array containing all of the key/value pairs so returned.
The array passed as argument is unchanged.
Reference

array_walk_recursive

array_walk_recursive (array, callback, param)
where:
arrayis the original array to process
callbackis the user callback function which will be automatically scheduled to process each of the item of the original array, and return a value. If an item is an array, the callback function processes each of its item recursively
paramoptional -- is a parameter that can be passed to the callback function
The array_walk_recursive applies the user callback function to avery item of an array, like the array_walk function above, but does it recursively, i.e. when an item is an array, the function also is applied to it.
The array passed as argument is unchanged.
Reference

3.9.4 File system functions

Some of the file system functions are presented in the following. Many more are described in the reference manual.
 
Data access
fclosecloses a file
feoftests for end of file condition
fgetsgets a line from a file, limited to a specified number of bytes
fgetssgets the next line from a file, and strips HTML tags
filereads the lines of the entire file into an array
file_get_contentsreads entire file into a string
file_put_contentswrites a string into a file
flushwrites out all file outputs still held in the buffers
fopenopens a file
freadreads a file into a string
fseekpoints to a position in a file
ftellreturns the current position in a file
ftruncatetruncates a file
fwritewrites binary data to a file
readfilereads a file and writes it out
 
File management
basenamereturns the filename component (right most part) of the file path
dirnamereturns the directory name component of a path
file_existstests whether a file exists
filesizereturns file size
filetypereturns file type
flocklock protects a file
is_dirtests whether a name is a directory name
is_executabletests whether a file is executable
is_filetests whether a name is the name of an file
is_linktests whether a name is a link
is_readabletests whether a name is the name of a readable file
is_uploaded_filetests whether a name is the name of an uploaded file
is_writabletests whether a name is the name of a writable file
realpathreturns the absolute path name from a relative path
 
Environment management
copycopies a file
fileatimereturns last access time to a file
filectimereturns last inode change time of a file
fstatreturns statistics about a file
mkdirmakes a directory
move_uploaded_filemoves an uploaded file
renamerenames a file or directory
rmdirremoves a directory
statreturns the statistics about a file
tempnamecreates a file with a unique name
tmpfilecreates a temporary file
touchsets access and modification times on a file
unlinkdeletes a file
 
File security
chgrpchanges the file group
chmodchanges the file mode
chownchanges the file owner
filegroupreturns file group
fileinodereturns file inode
filemtimereturns file modification time
fileownerreturns file owner
filepermsreturns file permissions

Data access

fclose

fclose (handle, , )
where:
handleis a file handle such as returned by an fopen function

The function closes the file identified by its handle. It returns true if the closing was successful, false otherwise.
Reference

feof

feof (handle)
where:
handleis a file handle such as returned by an fopen function

The function returns true if the end-of-file in the file is reached or an error occurred, false otherwise
Reference

fgets

fgets (handle, length)
where:
handleis a handle such as returned by an fopen function, that identifies the file to read
lengthoptional -- length is the number of bytes to read, plus 1 (number + 1). If omitted, defaults to 1024.

The function returns the next line, i.e. the sequence of bytes starting at the current line pointer and ending at a new-line or an end-of-file character, limited to (length -1) bytes (the reading stops when this number of bytes is reached before the new-line or end-of-file). The file pointer is advanced to the position just beyond the last character read. A boolean false is returned if the reading fails.
Reference

fgetss

fgetss (handle, length, preserved_tags)
where:
handleis a handle such as returned by an fopen function, that identifies the file to read
lengthlength is the number of bytes to read, plus 1 (number + 1)µ. If omitted, defaults to 1024.
preserved_tagsoptional -- is the list of the HTML or PHP tags to be preserved

The function reads the next line from the file, as the fgets function does. It then strips the read in line of all HTML and PHP tags. If the list of preserved tags is specified, the specified tags are not stripped. The result is returned.
Reference

file

file (file_uri, include_option)
where:
file_uriis the URI of the file to process
include_optionoptional -- is a boolean which, when true causes the named file to be searched for in the PHP include directory.

The file as identified by its URI is read into an array, with each line an item of the array. The new-line character is kept with each line. If the include_option argument is true, the URI is evaluated relative to the PHP include directory.
Reference

file_get_contents

file_get_contents (file_uri, include_option)
where:
file_uriis the URI of the file to process
include_option(optional) is a boolean which, when true causes the named file to be searched for in the PHP include directory.

The file as identified by its URI is read entirely into a string, and returned as the function result.
Reference

file_put_contents

file_put_contents (file_uri, string, flags)
where:
file_uriis the URI of the file to process
stringis the string to write out to the file
flags(optional) is a comma separated list of flags that control the writing. The possible values, which may be combined, are:
FILE_APPENDappend the string to the existing contents of the file (if not present, the string replaces the old contents)
FILE_USE_INCLUDEthe file URI is evaluated relative to the PHP include directory

The specified string is written out to the file as identified by its URI, in the mode describe by the flags. In all events, the file is created if it did not exist.
Reference

This function is not available with PHP 4. Use the equivalent combination fopen, fwrite, fclose instead.

flush

flush ( )
with no argument

The function flushes all outstanding output files (writes out the buffers and clear them). It returns nothing.
Reference

fopen

fopen (file_uri, mode)
where:
file_uriis the URI that identifies a file
modeis the mode in which the file is to be opened. The possible basic modes are defined by these notations:
ropen for read only, file pointer set at the beginning of the file
r+open for read and write, file pointer set at the beginning of the file
wopen for write only -- if file existed, is erased, if not, is created
w+open file for write and read -- if file existed, is erased, if not, is created
aopen file for append (file pointer set at the end of existing data) -- if file did not exist, is created
a+open file for append and read (file pointer set at the end of existing data) -- if file did not exist, is created
xcreate and open file for write only -- return false if file already existed, and raise an error condition
x+create and open file for write and read -- return false if file already existed, and raise an error condition
Additional qualifications can be added to the basic mode by appending a letter to the above code:
bthe data are treated as binary, i.e. no translation occurs when reading or writing
ttext mode, where the line-feed \n and line-feed-carriage-return \n\r codes are translated
Example: fopen ("http://www.myhost.com/myfile.txt", "rb")

The function returns a handler which represents the file as defined by its URI, in the mode specified by the second argument. Depending on an option of the PHP configuration, the fopen can operate on remote files, or is resticted to local files.
Reference

fread

fread (handle, length)
where:
handleis the handle that identify the file to process
lengthis the number of bytes to read

The function returns the number of bytes specified by the argument, or contained in the file, which ever is the smaller.
Reference

fseek

fseek (handle, offset, whence)
where:
handleis the handle that identify the file to process
offsetis the offset of the new position
whenceoptional -- defines from where the offset is evaluated. The possible values are:
SEEK_SETthe offset is from the beginning of the file -- this is the default
SEEK_CURthe offset is from the current position
SEEK_ENDthe offset is from the end-of-file (its value must be negative)

The function sets the file pointer to the position defined by the arguments, and returns true if the operation was successful, false if it failed.
Reference

ftell

ftell (, handle)
where:
handleis the handle that identify the file to process

The function returns the current value of the file pointer. If the operation fails, the function returns false
Reference

ftruncate

ftruncate (handle, size)
where:
handleis the handle that identify the file to process
sizeis the size to which the file is truncated.

The function truncates the file to the specified size and returns true on success, false on failure. This only affects the file as appears to the script (a subsequent file_get_contents will get the truncated file contents), not the physical external file.
Reference

fwrite

fwrite (handle, string, length)
where:
handleis the handle that identifies the file to write to -- in Windows systems, the file must have been opened with the 'b' option
stringis the string to write out
numberoptional -- specifies the maximum number of bytes to write out

The function writes out the binary contents of the string to the output file. If the operation is successful, the number of the bytes written out is returned. Otherwise, false is returned.
Reference

readfile

readfile (file_uri, include_option)
where:
file_uriis the URI which identifies the file to be processed
include_optionoptional -- if set to true, the URI is evaluated relative to the PHP include directory

The function reads in the file identified by its URI, and writes it to an output buffer. If the operation is successful, the function returns the number of bytes read from the file. The value false is returned, if the operation fails.
Reference

File management

basename

basename (path_name, suffix)
where:
path_nameis the path name to process
suffixoptional -- is the suffix to cut off

The function returns the filename component of the path, i.e. the rightmost component. If the suffix argument is specified, it is cut off from the file name when the latter has that suffix.
Reference

dirname

dirname (path)
where:
pathis a path name

The function returns the directory part of the path name, i.e. with the rightmost component removed.
Reference

file_exists

file_exists (filename)
where:
filenameis the name of a file. This can be a relative or absolute URI. In Windows systems, slashes or backslashes can be use to separate directory names.

The function returns true if the file exists
Reference

filesize

filesize (file_uri)
where:
file_uriis the URI of the file to process

The function returns file size, i.e. the number of characters contained in the file.
Reference

filetype

filetype (uri)
where:
uriis a URI.

The function returns the type of file identified by the URI, which can be: file, dir, link, fifo, char, block, unknown, or false if an error occurred.
Reference

flock

flock (handle, level, &block)
where:
handleis the file handle which identifies the file to lock
level is the desired protection level:
LOCK_SHshared (reader) lock
LOCK_EXexclusive (write) lock
LOCK_UNshared or exclusive lock
LOCK_NBnon blocking lock
&blockoptional -- is a variable passed by reference which receives the value true when the lock would block

The function lock protects the identified file
Reference

is_dir

is_dir (uri)
where:
uriis a URI

The function returns true if the specified URI identifies a directory
Reference

is_executable

is_executable (uri)
where:
uriis a URI

The function returns true if the specified URI identifies an executable file
Reference

is_file

is_file (uri)
where:
uriis a URI

The function returns true if the specified URI identifies an existing file
Reference

is_link

is_link  (uri)
where:
uriis a URI

The function returns true if the specified URI identifies an existing link
Reference

is_readable

is_readable (uri)
where:
uriis a URI

The function returns true if the specified URI identifies a readable file
Reference

is_uploaded_file

is_uploaded_file (uri)
where:
uriis a URI

The function returns true if the specified URI identifies an uploaded file
Reference

is_writable

is_writable (uri)
where:
uriis a URI

The function returns true if the specified URI identifies a writable file
Reference

realpath

realpath (relative_uri)
where:
relative_uriis the relative URI of a local file.

The function returns the absolute path of the file identified by the specified relative path, if it exists, or false if the file does not exist, or the function fails for any other reason.
Reference

File management

copy

copy (source_uri, dest_uri)
where:
source_uriis the URI of an existing file, to be copied
dest_uriis the URI of the file to be created

The function creates the file with dest_uri as its URI. Some special considerations are:

-if the destination file already exists, it can be overwritten if overwriting is authorized by the PHP options
-depending on the PHP option, one or both URIs can refer to a remote file
The function returns true if the operation is successful, or false if it fails.
Reference

fileatime

fileatime (file_uri)
where:
file_uriis the URI of the file to query

The functions returns the time the file was last accessed, as a Unix timestamp, or false if the operation fails.
Reference

filectime

filectime (file_uri)
where:
file_uriis the URI of the file to query

The functions returns the time the file was last changed, as a Unix timestamp, or false if the operation fails.
Reference

fstat

fstat (handle)
where:
handleis a handle such as returned by an fopen function, that identifies a file

The function returns the statistics about the file identified by the handle.
Reference

mkdir

mkdir (dir_uri, mod)
where:
dir_uriis the local URI of the directory
modis a 4-digit octal representation of the permissions on the directory, in the form:
0xyzwhere x represents the permissions granted to the owner, y the permissions granted to the owner's group, z the permissions granted to all
each category of user can have none, or one or more of the following permissions, each of which is assigned a number as follows:
4 - permission to read
2 - permission to write
1 - permission to execute
To grant one or more of these permissions, add the corresponding number. For example, to grant to the owner:
- no permission: x = 0
- permission to read and write: x = 4 + 2 = 6

The function creates the directory with the specified URI, and grants permissions on the directory to the owner, the owner's group, and to all, as specified by the mod argument. The value true is returned if the directory is successfully created. Otherwise, false is returned.
Reference

move_uploaded_file

move_uploaded_file (source_uri, dest_uri)
where:
source_uriis the URI of the uploaded file to move
dest_uriis the URI of the file in its new location

The function moves the uploaded file from its position located by the source_uri argument to the new position located by the dest_uri argument. If the operation is successful, a true value is returned. The source file must be a moveable file that was uploaded to the server, otherwise a false value is returned and no operation is performed.
Reference

rename

rename (old_uri, new_uri)
where:
old_uriis the old URI of the file or directory to rename
new_uriis the new URI of the file or directory

The function operates on a file or a directory. It changes the file or directory old URI to the new URI. This can effectively move the file or directory to another directory. If the operation is successful, the function returns the value true. Otherwise it returns the value false.
Reference

rmdir

rmdir (dir_uri)
where:
dir_uriis the URI of the directory to remove

The function removes the directory identified by its URI. The directory must be empty. If the operation is successful, the function returns true. Otherwise its returns false.
Reference

stat

stat (file_uri)
where:
file_uriis the URI fo the file to process.

The function returns the statistics about the file. Note that the file need not be opened.
Reference

tempnam

tempnam (dir_uri, prefix, )
where:
dir_uriis the URI where the file is to be created
prefixis the prefix assigned to the file name

The function creates a file with a unique name starting with the specified prefix. The file is not necessary created in the specified directory. The directory where the file is created is rather determined by the operating sytem. In Windows, it is usually the C:\Windows\Temp\ directory.
Reference

tmpfile

tmpfile ( )
No argument

The function creates a temporary file in write mode, and returns its handle. The file is removed when closed, or when the script terminates.
Reference

touch

touch (file_uri, mtime, atime)
where:
file_uriis the URI of the file to process
mtimeoptional -- is the modification time; defaults to the current timestamp
atimeoptional -- is the access time; default to the current timestamp

The function attempts to set the access and modification times of the file to the specified values, and returns true if the operation is successful, false otherwise.
Reference

unlink

unlink (file_uri)
where:
file_uriis the URI of the file to process.

The function attemps to delete the file identified by the specified URI, and returns true if successful, false otherwise.
Reference

File security

chgrp

chgrp (file_uri, new_group)
where:
file_uriis the URI of the file to process.
new_group is the name or number of the group to which the file is to be assigned

The function assigns the file to the new group identified by the second argument.
Reference

chmod

 (file_uri, mode)
where:
file_uriis the URI of the file to process.
modeis the new mode as an octal number in the form: 0xyz where each of the x, y and z is an octal digit from 0 to 7, and represents the permission to access the file by the owner, the file group, and everybody, respectively

The function attempts to change the mode of the file to the new value specified by mod argument, and returns true if successful, false otherwise.
Reference

chown

chown (file_uri, user)
where:
file_uriis the URI of the file to process.
useris the name or number identifying a user

The function attempts to assign the user defined by the second argument as the new owner of the file, and returns true if successful, false otherwise.
Reference

filegroup

filegroup (file_uri)
where:
file_uriis the URI of the file to process.

The function returns the numerical ID of the group to which the file pertains. Returns false if the operation fails.
Referencereturns file group

filemtime

filemtime (file_uri)
where:
file_uriis the URI of the file to process.

The function returns the time of the last modification to the file, as a timestamp, or false if the operation fails.
Reference

fileowner

fileowner (file_uri)
where:
file_uriis the URI of the file to process.

The function returns the ID of the file owner, in numerical format, or false if the operation fails.
Reference

fileperms

fileperms (file_uri)
where:
file_uriis the URI of the file to process.

The function returns the permissions on the file, as an octal number of the form 0xyz where x, y, z are the permissions granted to the owner, the file group, and every body, respectively.
Reference

3.9.5 Variable functions

Some of the functions that process a variable are:
floatvalreturns the float value of the variable
gettyperetuns the type of the variable
intvalreturns the integer value of the variable
is_arrayreturns true if the variable contains an array
is_boolreturns true if the variable contains a booelan
is_callablereturns true if the variable contains a callable function
is_floatreturns true if the variable contains a float
is_intreturns true if the variable contains an integer
is_nullreturns true if the variable contains a null
is_numericreturns true if the variable contains a number
is_objectreturns true if the variable contains an object
is_resourcereturns true if the variable contains a resource (as returned by certain functions
is_scalarreturns true if the variable contains a scalar
is_stringreturns true if the variable contains a string
issetreturns true if the variable has been assigned a value
print_rdisplays the type and value of the variable
serializeserializes the variable and returns the serialized value in a string
strvalreturns the string value of the variable
unserializerestore the original variable from its serialized string
unsetstrips the variable of its value, making it unset
var_dumpdisplays the type and values of the variable

Complete description is to be found in the Reference Manual.

floatval

Syntax:
floatval ($var_name)
where:
var_nameis the name of the variable processed by the function.
The function returns the float value of the data contained in the variable.

gettype

Syntax:
gettype ($var_name)
where:
var_nameis the name of the variable processed by the function.
The function returns the type of the data contained in the variable

intval

Syntax:
intval ($var_name)
where:
var_nameis the name of the variable processed by the function.
The function returns the integer value of the data contained in the variable

is_array

Syntax:
is_array ($var_name)
where:
var_nameis the name of the variable processed by the function.
The function returns true if the data contained in the variable is an array

is_bool

Syntax:
is_bool ($var_name)
where:
var_nameis the name of the variable processed by the function.
The function returns true if the data contained in the variable is a boolean

is_callable

Syntax:
is_callable ($var_name)
where:
var_nameis the name of the variable processed by the function.
The function returns true if the data contained in the variable is a callable function

is_float

Syntax:
is_float ($var_name)
where:
var_nameis the name of the variable processed by the function.
The function returns true if the data contained in the variable is a float

is_int

Syntax:
is_int ($var_name)
where:
var_nameis the name of the variable processed by the function.
The function returns true if the data contained in the variable is an integer

is_null

Syntax:
 ($var_name)
where:
var_nameis the name of the variable processed by the function.
The function returns true if the data contained in the variable is null

is_numeric

Syntax:
is_numeric ($var_name)
where:
var_nameis the name of the variable processed by the function.
The function returns true if the data contained in the variable is a number

is_object

Syntax:
is_object ($var_name)
where:
var_nameis the name of the variable processed by the function.
The function returns true if the data contained in the variable is an object

is_resource

Syntax:
is_resource ($var_name)
where:
var_nameis the name of the variable processed by the function.
The function returns true if the data contained in the variable is a resource as returned by certain functions

is_scalar

Syntax:
is_scalar ($var_name)
where:
var_nameis the name of the variable processed by the function.
The function returns true if the data contained in the variable is a scalar

is_string

Syntax:
is_string ($var_name)
where:
var_nameis the name of the variable processed by the function.
The function returns true if the data contained in the variable is a string

isset

Syntax:
isset ($var_name)
where:
var_nameis the name of the variable processed by the function.
The function returns true if the the variable has been assigned a value. See also unset

print_r

Syntax:
print_r ($var_name)
where:
var_nameis the name of the variable processed by the function.
The function displays the type and value(s) of the variable

serialize

Syntax:
serialize ($var_name)
where:
var_nameis the name of the variable processed by the function.
The function serializes the contents of a variable and returns the result as a string that can be transmitted on a communication link, or recorded in a data file or database. The serialized result can be unserialized to restore the data to its original form.

strval

Syntax:
strval ($var_name)
where:
var_nameis the name of the variable processed by the function.
The function returns the string value of the data contained in the variable

unserialize

Syntax:
unserialize ($serial_str)
where:
serial_stris a string returned by the serialize function, or the name of a variable containing such a string.
The function returns the original data from which the processed string was obtained.
When unserializing an object, the class of the object must be included in the script.

unset

Syntax:
unset ($var_name)
where:
var_nameis the name of the variable processed by the function.
The function strips the variable of its value, making is unset. It isset value is then false.

var_dump

Syntax:
var_dump ($var_name)
where:
var_nameis the name of the variable processed by the function.
The function displays the type and value(s) of the variable.

3.9.6 PHP options and informations functions

The functions in this category inform on the PHP initialization directives, and can modify certain of them during run time. Some of these functions are:
ini_get
ini_set
phpinfo
set_time_limit
The complete description is to be found in the Reference manual

ini_get

 ini_get (var_name)
where:
var_nameis the name of the configuration directive to query
The function returns the current value of the directive. A boolean value is returned as an empty or 0 when off, 1 when on

ini_set

ini_set (var_name, value)
where:
var_nameis the name of the configuration directive to query
valueis the new value to assign to the directive
Only the directives marked as PHP_INI_ALL or PHP_INI_USER changeable, in the directive list of the ini_set description, can be changed by ini_set
The function returns the old value on success, the value false on failure. When the old value was false you cannot tell what happened by merely testing the return value. An ini_get must be executed for the new value

phpinfo

phpinfo (category)
where:
categoryis an optional argument which indicates which information category the function is to return. The possible values are the constants to be found in the Reference manual, in the description of the phpinfo function
When the argument is omitted, the function returns all of the information.

set_time_limit

set_time_limit (seconds)
where:
secondsis the number of seconds the script is allowed to run, from the time the function is executed.
If the value is 0, NO time limit is set

3.9.7 Miscellaneous functions

Some of the functions categorized under this heading are:
constantreturns the value of a named constant
definedefines a constant
definedreturns true if a constant with the given name has been defined
dieterminates the script and displays a message (this is an alias of exit
evalreturns the value evaluated by the expression passed as an argument
exitterminates the script and displays a message
packpacks a set of numbers originally presented in an extended form of one octet per digit
sleepdelays the execution of the script for a number of seconds
time_nanosleepdelays the execution of the script for a number of seconds and nanoseconds
unpackrestores a packed set of numbers into its original form
usleepdelays the execution of the script for a number of microseconds
The complete description is to be found in the Reference manual

The eval function

eval

eval (expression)
where:
expressionis the expression to evaluate, or the variable which contains this expression
The function returns the result of evaluating the expression
Reference.

Script execution control

exit

exit (message)
where:
messageis the message to display
The function terminates the script and displays the specified message
Reference.

die

die (message)
where:
messageis the message to display
The function terminates the script and displays the specified message -- this is an alias for exit
Reference.

sleep

sleep (seconds)
where:
secondsis the number of seconds for which to delay the script
The function delays the execution of the script for the number of specified seconds.
Reference.

usleep

usleep (microseconds)
where:
microsecondsis the number of microseconds for which the script is to be delayed
The function delays the execution of the script by the specified number of microseconds
Reference.

time_nanosleep

time_nanosleep (seconds, nano)
where:
secondsis the number of seconds for which to delay the execution of the script
nanois the number of nanoseconds to add to the delay
The function delays the execution of the script by the number of specified seconds ans nanoseconds
Reference.

Constant functions

define

define (name, value, case_insensitive)
where:
nameis the name of the constant to be defined -- uppercase is recommmended -- names starting with 2 underscores ("_") are to be avoided
valueis the value assigned to the constant -- this value must be a scalar
optionnal -- boolean value: when true the constant value is case insensitive -- the default is false (the constant is case sensitive)
The function returns true> on success, false on failure.
Reference.

defined

defined (name)
where:
nameis a name to query
The function returns true if the name is that of a constant, false otherwise.
Reference.

constant

constant (name)
where:
nameis the name of a constant or a variable containing it
The function returns the value of the constant, or false if the name is not that of a constant.
Reference.

Pack and unpack

pack

pack ("format)","list)"
where:
formatis a string of format elements which define how the strings in the list are to be processed.
listis a comma separated list of strings of data to be processed
There are 2 types of format elements:
- the data packing format elements
- the character inserting/deleting format elements

Each of the data packing format elements applies to one of the data string in the data string list. These format elements are:
anreturn the first n characters of the string, right padding with NUL
Anreturn the first n characters of the string, right padding with SPACE
hnpack the first n digits, 2 into one octet, lower order nibble first
Hnpack the first n digits, 2 into one octet, higher order nibble first
cpack a number from 0 to 255 into one octet, greater numbers are treated modulo 256
Csame as c
spack a number from 0 to 65535 into 2 octets, greater numbers are treated modulo 65536, in machine dependent order
Ssame as s
vpack a number from 0 to 65535 into 2 octets, greater numbers are treated modulo 65536, lower order octet first
npack a number from 0 to 65535 into 2 octets, greater numbers are treated modulo 65536, higher order octet first
ipack an integer into hexadecimal form, with machine dependent number and order of octets
Isame as i
lpack a number from 0 to 4294967295 into 4 octets, greater numbers are treated modulo 4294967296, in machine dependent order
Lsame as l
Vpack a number from 0 to 4294967295 into 4 octets, greater numbers are treated modulo 4294967296, lower order octet first
Npack a number from 0 to 4294967295 into 4 octets, greater numbers are treated modulo 4294967296, higher order octet first
fpack a float into its hexadecimal form, with machine dependent octet number and order
dpack a float into its hexadecimal form, with machine dependent octet number and order
The original numbers are string representation, with one octet per digit. With the a and A format the characters are not transformed, only a right padding occurs when the original string is short. With the h and H formats, the characters from the original string, which must represent hexadecimal digits ('0' to '9', 'A' to 'F'), are transformed by pair, each pair compacted into one octet. The remaining formats transform one number at a time, changing from the character representation to the binary representation.

The number n appended to the a, A, h or H format element specifies the number of characters from the original string to be processed. With h and H it must not exceed the number of characters in the original string. An asterisk sign(*) can be used for n; it indicates that all of the characters from the original string are to be processed -- a* or A* therefore result in a simple copy without transformation.

A number n can be appended to the other format elements to indicate the number of times the element is to be repeated, to be applied to successive data strings. An asterisk sign (*) can be used for n; it indicates that the element is to be repeated as needed to match the remaining number of data strings in the argument list; it therefore can be used only with the last element in the format.

A format element of the data packing type, at a certain rank in the format, applies to the data string of the same rank in the argument list. Therefore the number of format elements of this type (counting each element as many times as it is repeated), must match the number of strings in the argument list.

Further details on how each of the format element works are given below.

The character inserting/deleting format elements add or remove characters into or from the result The character inserting/deleting format elements define what is to be done the the result as attained when they are encountered. These elements are:

xadd a NUL character to the result string obtained so far, at the position where the element is
Xremove one character from the right end of the result string obtained so far
@padds NUL characters from the end of the result string obtained so far, to the absolute position defined by p
The number p appended to the @ format element indicates the position upto which NULs are to be added to the result string.

A number n can be appended to the x or X format element to repeat it n times (i.e. add n NULs, or remove n characters, respectively).

Here are the details on how the data packing format elements are coded and work.

anwhere:
ais the format element code, to appear 'as is'
nis the number of characters to return -- default: to 1
Right NUL padding: the first n characters of the processed string are returned -- if the processed string is shorter than n the result is padded on the right with NUL characters (hexadecimal 00)
Anwhere:
Ais the format element code, to appear 'as is'
nis the number of characters to return -- default: to 1
Right SPACE padding: the first n characters of the processed string are returned -- if the processed string is shorter than n the result is padded on the right with SPACE characters (hexadecimal 20)
hnwhere:
his the format element code, to appear 'as is'
nis the number of characters from the string to process
Packing 2 hexadecimal digits into 1 octet, with the rightmost digit into the left nibble. The figures from '0' to '9' are transformed into the 0 to 9 hexadecimal nibbles, the letters from 'A' (or 'a') to 'F' or ('f') into the A to F hexadecimal nibbles.
The string is processed from left to right. Each pair of digits is packed into one octet which is added to the result. If the string has an odd number of digits, a '0' is appended to the last digit to make the last pair. The processed characters in the string must be hexadecimal digits: figures from '0' to '9', letters from 'A' to 'F'.
Hnwhere:
His the format element code, to appear 'as is'
nis the number of characters from the string to process
Packing 2 hexadecimal digits into 1 octet, with the rightmost digit into the left nibble. The figures from '0' to '9' are transformed into the 0 to 9 hexadecimal nibbles, the letters from 'A' (or 'a') to 'F' or ('f') into the A to F hexadecimal nibbles.
The string is processed from left to right. Each pair of digits is packed into one octet which is added to the result. If the string has an odd number of digits, a '0' is appended to the last digit to make the last pair. The processed characters in the string must be hexadecimal digits: figures from '0' to '9', letters from 'A' to 'F'.
cnwhere:
c(lower case) is the format element code, to appear 'as is'
nis the number of times the format element is repeated (this number of data strings are packed using c).
Packing a tiny number into one octet. The number recognized at the beginning of the string, modulo 256 is extracted -- this is a number from 0 to 255 representable by a 2-digit hexadecimal number; this number is returned as a 1-octet result. For example, the string '266XYZ' would yield the hexadecimal '0a'.
Cnwhere:
C(upper case) is the format element code, to appear 'as is'
nis the number of times the format element is to be repeated (this number of data strings are packed using C).
Packing a tiny number into one octet. The result is the same as with c (lower case).
snwhere:
sis the format element code, to appear 'as is'
nis the number of times the format element is to be repeated (this number of data strings are packed using s).
Packing a short integer into 2 octets (16 bits), in machine dependent octet order. The number recognized at the beginning of the string, modulo 65536, is extracted -- this number is represented by a hexadecimal number of 2 octets which are returned as a result.
Snwhere:
sis the format element code, to appear 'as is'
nis the number of times the format element is to be repeated.
Packing a short integer into 2 octets (16 bits), in machine dependent octet order -- same result as with s
nnwhere:
nthe first n -- is the format element code, to appear 'as is'
nthe second n -- is the number of times the format element is to be repeated.
Packing a short integer into 2 octets (16 bits), higher order octet first. The number recognized at the beginning of the string, modulo 65536, is extracted -- this number is represented by a hexadecimal number of 2 octets which are returned as a result.
vnwhere:
nthe first n -- is the format element code, to appear 'as is'
nthe second n -- is the number of times the format element is to be repeated.
Packing a short integer into 2 octets (16 bits), lower order octet first. The number recognized at the beginning of the string, modulo 65536, is extracted -- this number is represented by a hexadecimal number of 2 octets which are returned as a result.
inwhere:
iis the format element code, to appear 'as is'
nis the number of times the format element is to be repeated.
Packing a full integer, machine dependent length and order -- usually 32 bits, but can be 64 bits. The number recognized at the beginning of the string, is extracted -- this number is returned in its hexadecimal representation
Inwhere:
Iis the format element code, to appear 'as is'
nis the number of times the format element is to be repeated.
Packing a full integer, machine dependent length and order -- same result as with i.
lnwhere:
lis the format element code, to appear 'as is'
nis the number of times the format element is to be repeated.
Packing a full integer into 4 octets (32 bits), in machine dependent octet order. The number recognized at the beginning of the string, modulo 4294967296, is extracted -- this number is represented by a hexadecimal number of 4 octets which are returned as a result.
Lnwhere:
Lis the format element code, to appear 'as is'
nis the number of times the format element is to be repeated.
Packing a full integer into 4 octets (32 bits), in machine dependent octet order. Same result as with l
Nnwhere:
Nis the format element code, to appear 'as is'
nis the number of times the format element is to be repeated.
Packing a full integer into 4 octets (32 bits), in higher octet first order. The number recognized at the beginning of the string, modulo 4294967296, is extracted -- this number is represented by a hexadecimal number of 4 octets which are returned as a result.
Vnwhere:
Vis the format element code, to appear 'as is'
nis the number of times the format element is to be repeated.
Packing a full integer into 4 octets (32 bits), in lower octet first order. The number recognized at the beginning of the string, modulo 4294967296, is extracted -- this number is represented by a hexadecimal number of 4 octets which are returned as a result.
fnwhere:
fis the format element code, to appear 'as is'
nis the number of times the format element is to be repeated.
Packing a float into its hexadecimal representation.
dnwhere:
dis the format element code, to appear 'as is'
nis the number of times the format element is to be repeated.
Packing a double into its hexadecimal representation.

Reference.

unpack

The unpack function accepts a character string and processes it according to a format. Results are returned in an array.

With the a and A formats, it removes the NUL and SPACE characters as requested. With the h and H formats, it unpacks each octet of the processed string into 2 octets, each representing in ASCII code, the hexadecimal number contained in one of the original octet nibble. With h the lower order nibble, i.e. the one on the right of the octet comes first (i.e. on the left) in the result; with H, the order is reversed.

With these formats, the result is one string, returned in a one-item array.

Each of the remaining formats extracts the hexadecimal numbers contained in the processed string, and returns them in ASCII character presentation. Each hexadecimal number is the contents of one, two, four or more octets, depending on the format and the machine. The processed string is cut up into chunks of the applicable number of octets, and the hexadecimal number contained in the successive chunks are returned in the result array, in decimal character format, with each digit represented by one ASCII character. The number n appended to the format element code indicates the number of numbers to return. An asterisk sign (*) can be used for n to indicate that all the numbers up to the end of the string are to be retrieved. When the string does not contain the exact number octets for the unpacked numbers, the missing octet for the last number are supplemented by '0'.

The details of the format elements are as follows (in the first column, the letters on the left are the format element codes, similar to those used with the pack function, the n is the repetition number that was explained above):

anreturn the first n characters of the string, removing the NULs
Anreturn the first n characters of the string, replacing consecutive SPACEs by one SPACE
hnreturn the first n digits, 2 from each octet, lower order nibble first -- n rounded to the lower even value
Hnreturn the first n digits, 2 from each octet, higher order nibble first -- n rounded to the lower even value
cnreturn the numbers contained in successive octets, signed (value -128 to 127)
Cnreturn the numbers contained in successive octets, unsigned (value 0 to 255)
snreturn the numbers contained in successive octet pairs, interpreted in machine defined octet order, signed (value -32768 to 32767)
Snreturn the numbers contained in successive octet pairs, interpreted in machine defined octet order, unsigned (value 0 to 65535)
vnreturn the numbers contained in successive octet pairs, interpreted in lower order first order, unsigned (value 0 to 65535)
nnreturn the numbers contained in successive octet pairs, interpreted in higher order first order, unsigned (value 0 to 65535)
inreturn the successive integers, each integer with machine dependent number and order of octets (if the number was packed with the i or I format, the octet number and order will match), signed
Inreturn the successive integers, each integer with machine dependent number and order of octets (if the number was packed with the i or I format, the octet number and order will match), unsigned
lnreturn the numbers contained in successive 4-octet groups, interpreted in machine dependent order, signed (value -2147483648 to 2147483647)
Lnreturn the numbers contained in successive 4-octet groups, interpreted in machine dependent order, unsigned (value 0 to 4294967296)
Vnreturn the numbers contained in successive 4-octet groups, interpreted in lower order octet first order, signed (value -2147483648 to 2147483647)
Nnreturn the numbers contained in successive 4-octet groups, interpreted in lower order octet first order, unsigned (value 0 to 4294967296)
fnreturn the successive float numbers
dnreturn the successive double numbers

Reference.

3.10 Class and object

3.10.1 Class definition

Syntax:
class class_name {
  visible $property_name = value;
  
  function __construct (arguments) {
    php statements
  }

  visible function method_name (arguments) {
    php statements
  }
}
Example:
<?php
class SampleCircle {

  private $pi  = 3.14159265;
  public  $rad = 0;

  function __construct ($x) {
   $this -> rad = $x;
  } //end construct

  function area () {
   $x = $this->pi*$this->rad*$this->rad;
   return $x;
  }//end area

  function perimeter () {
   return 2 * $this -> pi * $this->rad;
  }
}//end SampleCircle
?>
 
class_nameis the name you assign to the class
visiblecan take on one of the values:
public
protected
private
property_nameis the name you assign to the property being defined -- zero, one or more properties may be defined -- a property is a variable defined in a class
valueis the value initially assigned to the property named on the left of the = sign.
__constructis the name of the constructor function (always this name, as of PHP 5)
method_nameis the name you assign to an optional method of the class -- zero, one or more methods may be defined -- a method is a functions defined in a class. It is defined using the same syntax as for ordinary function, except that its definition can be preceded by the visible property

Properties and methods are members of the class.

Example:
The class is named SampleCircle
It has:
- 2 properties: $pi and $rad
- 2 methods: area and perimeter

The class has a constructor function which assigns a value to the $rad property.
A property is referred to from within the class using the notation:
$this -> property_name
Please note that there is no $ sign before the property name.

Class constructor

The constructor function is called each time the class is instanciated.
As of PHP 5 the constructor function is named __construct (2 underscores as the first characters). There can be only one constructor (no redeclaration allowed).

To allow for compatibility with older versions, a constructor function having the same name as the class is accepted. In this example, it would be function SampleCircle ($x) { ... }.

Class destructor

The destructor function is called before the class object is destroyed.
As of PHP 5 the destructor function is named __destruct (2 underscores as the first characters). It can take on no argument.

Class property

A variable included in a class is called a property.
A property name must be preceded by one of the keywords which determines its visibility. These keywords and their meanings are:
publicthe property can be accessed from anywhere
protectedthe property can be accessed from the class or one of its extensions
privatethe property can be accessed only from within the class
The value of a property can be:
-a scalar
-an array
-an object

Class method

A function defined in a class is called a method. It has the same syntax as an ordinary function, except that its definition can start with a keyword that specifies its visibillty. The possible values of this keyword are:
publicthe method can be accessed from anywhere (this is the default)
protectedthe method can be accessed from the class or one of its extensions
privatethe method can be accessed only from within the class

Class this

The $this notation is used to designate the object created from the class, from a function within it:
- a property of the classis denoted $this -> property_name
- a method of the classis denoted $this -> method_name

Static members

A static member is declared using the static keyword:
visibility static property_name
visibility static method_name (...) {
   ...
}
where:
visibilityis the visibility attribute, which can be have one of the values public (this is the default), private, protected
property_nameis the name of the declared property, which can be assigned a value, as any ordinary property
method_nameis the name of the declared method, which is defined as any other method

A static member is referenced from within the class using the self keyword and the :: (double colon) operator:

self::property_name
self::method_name
where:
property_nameis the name of the referenced property
method_name (...)is the name of the referenced method
A static member is referenced from outside the class using the class name and the :: operator:
class_name::property_name
class_name::method_name (...)
where:
class_nameis the name of the class to which the property or method pertains
property_nameis the name of the referenced property
method_name (...)is the name of the referenced method

Constant members

A constant member is declared using the const keyword:
const constant_name=value
where:
constant_nameis the name of the declared constant, which is assigned a unmodifiable value
valueis the unmodifiable value of the constant

A constant member is referenced from outside the class using the class name and the :: operator:
class_name::constant_name
where:
class_nameis the name of the class to which the constant pertains
property_nameis the name of the referenced constant

Class file

The class definition is to be set in a file to be included in the script that uses the class (it can also be hard coded anywhere in the script).
-this file can have any name
-it must be in a directory where the script processor can find the include elements. This can be the directory that contains the script, or any of the include directory of your PHP system.

Class autoload

The autoload function causes the classes required in a script to be automatically loaded. Its syntax is:
funtion __autoload ($arg) {
   require_once "$arg.suffix";
} 
where:
$argis any name (with the $ sign)
suffixis the file name extension of the names of the file holding the class definitions
.the dot between $arg and suffix is required as shown
The name __autoload starts with 2 underscores (__). Each class must be defined in individual files having:
- the name of the class
- the extension as specified in the __autoload function

The files are to be set in the same directory as the calling script, or in one of the include directories of your PHP system.

3.10.2 Class extension

Syntax:
class sub_name extends parent_name {

  visible $property_name = value;
  
  function __construct (arguments) {
    parent::__construct(parent_argument);
    php statements
  }

  function method_name (arguments) {
    php statements
  }
}
Example:
<?php
include "CircleFile.php";

class SampleCylinder extends SampleCircle {

  public  $height = 0;

  function __construct ($x, $y) {
   parent::__construct($x);
   $this -> height = $y;
  } //end construct

  function volume () {
   $v = $this->height * parent::area();
   return $v;
  }//end volume

  function area () {
    $h = $this->height * $this->perimeter();
    $b = 2 * parent::area();
    return $h + $b;
  }//end area

}//end SampleCylinder
?>
 
sub_nameis the name you assign to the extended class
parent_nameis the name of the parent class
Properties and methods of the parent class are part of the extended class, unless they are redefined in the latter.

Properties and functions (including the constructor) of the extended class are defined using the same syntax as shown in 3.10.1 above.

From a method in the extended class:

-properties and methods of the extended class are identified using the $this-> notation:
$this->property_namefor a property
$this->method_namefor a method
-properties and methods of the parent class are identified using the parent:: notation:
parent::property_namefor a property
parent::method_namefor a method

A property or method of the parent class that is not redefined in the extended class pertains to both the parent and the extended class, so that it can be identified with either the $this-> or the parent:: notation. In the example, the perimeter function can be identified using either notation:
$this -> perimeter()
parent::perimeter()

The parent class definition must be included in the script before the extended class can be defined. In the example, it is included in the script that contains the definition of the extended class.

3.10.3 Object

Object creation

Syntax:
$object_name = new class_name (arguments)
Example:
$cylinder = new SampleCylinder (100, 10);

object_nameis the name you assign to the created object
class_nameis the name of the class of which the object is to be an instance
argumentsare the values to be passed as arguments to the constructor function

Object property access

Syntax:
$object_name -> property_name
Example:
$cylinder -> rad
 
object_nameis the name of the object
property_nameis the name of the property -- the property must have the visibility of public
Note that there is a $ sign before the object name, none before the property name

Object method access

Syntax:
$object_name -> memthod_name (arguments)
Example:
$cylinder -> perimeter ( )
 
object_nameis the name of the object
method_nameis the name of the method -- the property must have the visibility of public
argumentsare the values of the method argument
Note that there is a $ sign before the object name, none before the method name


top Cover  Copyright  Contents  Reference  Index  previous  next