Cover
Copyright
Contents
Reference
Index
previous
next
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
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.1 Scalars
The four scalar types are:
boolean | boolean with value true of false (reserved words, case insensitive)
|
integer | integer -- size is platform dependent -- usually minimum: -2147483648 maximum: +2147483647. Example: 12345
|
float | a.k.a double, real number -- floating point number. Formats:
123.45
1.2345E+2
12345.e-2
|
string | character 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:
3.2.3 Special
Two special types:
resource | returned by some functions, like mysql_connect (returns a connection resource)
|
null | the only value is null (case insensitive)
|
3.2.4 Pseudo
Three pseudo-types are introduced by the reference manual, for presentation purpose:
mixed | data of any of several types
|
number | integer or float type
|
callback | a 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.1 Variable name
The name of a variable of any type has the following structure:
where:
$ | $ sign to appear as is
|
variable_name | the 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_name | name of the array; created if it did not exist
|
key | identification of a key, an integer or a string, enclosed within quotes if a string
|
value | value 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_name | name of the array being created
|
key | identification of a key, an integer or a string, enclosed within quotes if a string
|
value | value 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:
where the charaters in blue are to be coded "as is"; the variable values are:
array_name | name of the containing array
|
key | identification 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
This defines $x, $y and $z as global variables.
Using the $GLOBALS array
where:
var | is the name given to the variable (without the $ sign -- the variable is referenced as $ var.
|
value | is 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
|
$_GET | data from a form using the GET method
|
$_POST | data from a form using the POST method
|
$_COOKIE | data from the cookie sent in with the current message
|
$_REQUEST | data found in $_GET, $_POST and $_COOKIE
|
$_FILES | file information received from a file uploading form using the POST method
|
Data found in the surrounding system
|
$_SERVER | data from the server (includes HTTP header data from the request message)
|
$_ENV | data from the environment in which the PHP parser is running
|
Program data
|
$_SESSION | data from the session under which the script is running
|
$GLOBALS | data 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:
Keys | Values
| name | is the original name of the uploaded file
| type | is the data type of the uploaded file (e.g. 'text/thml')
| tmp_name | is the absolute path of the temporary file where the data are uploaded
| error | is the error level of the upload operation
| size | is 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_name | is the name of the variable to declare
|
initial_value | is 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
Modifying $bar also modiifes $foo
3.4.1 The define function
A constant is defined by a define function. Syntax:
define ("constant_name", "constant_value", case_insensitive) |
where:
constant_name | is the name of the constant to declare -- no $ sign precedes the name
|
constant_value | is the initial value of the constant
Only a scalar value (integer, float, string, boolean) is valid
|
case_insensitive | is 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.1 Arithmetic operations
Code | Signification | Example - 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
Code | Signification | Example - 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
Code | Signification | Example - with $a=15 $b=7 $c=0
|
|| | OR | $a || $b | result: true
|
or | OR | $a or $b | result: true
|
xor | Exclusive OR | $a xor $b | result: false
|
and | AND | $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
Code | Signification - 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
Code | Signification |
|
. | 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 += $b | stands for $a = $a + $b
|
$a -= $b | stands for $a = $a - $b
|
$a *= $b | stands for $a = $a * $b
|
$a /= $b | stands for $a = $a / $b
|
$a %= $b | stands for $a = $a % $b
|
$a .= $b | stands for $a = $a . $b
|
$a &= $b | stands for $a = $a & $b
|
$a |= $b | stands for $a = $a | $b
|
$a ^= $b | stands for $a = $a ^ $b
|
$a <<= $b | stands for $a = $a << $b
|
$a >>= $b | stands 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:
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.
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:
Expression | Unwonted 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.1 The if control structure
The complete syntax:
if (condition) {
if_statements
}
elseif (condition_1) {
elseif_statements_1
}
. . .
else {
else_statements
}
|
where:
condition | is a logical expression, or an expression of any type tested for its boolean value
| if_statements | is the set of statements executed if condition is true
| condition_1 | is a logical expression, or an expression of any type tested for its boolean value
| elseif_statements_1 | is 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_statements | is 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:
$var | is the switching variable
| const_1 | is a constant expression
| statements_1 | is the set of statements executed if the switching variable is equal to the constant const_1
| const_2 | is a constant expression
| statements_2 | is 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:
condition | is a logical expression or an expression of another type used for its boolean value -- tested before each loop
| loop_statements | is 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_statements | is the set of statements executed at each loop
| condition | is 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:
array | is an expression the value of which is an array
| $value | is a value extracted from the array as defined by the array expression
| $key | is a key extracted from the array as defined by the array expression (the second form extracts a key and its related value)
| statements | is 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_set | is the set of comma separated statements executed before the beginning of the first loop
|
condition | is 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_set | is the set of comma separated statements executed at the end of each loop
|
loop_body_statements | represents the set of statements (ending with semi-colons) executed if the condition is true
|
3.7.7 The break statement
Used in a switch, while, do, for or foreach statement set -- terminates the statement |
3.7.8 The continue statement
Used in a while, do, for or foreach statement set -- terminates the current loop, and schedules the next |
3.7.9 The return statement
where:
value | is 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.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:
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
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
|
bin2hex | returns the hexadecimal representation of a string
|
chr | returns a character of a given ASCII code
|
echo | outputs one or more strings
|
fprintf | writes out a string in a given format, to a specified stream
|
money_format | returns a number formatted into a currency representation
|
number_format | returns a formatted float number
|
ord | returns the ASCII code of the first character in a string
|
print | writes out a string
|
setlocale | sets the environment to use the presentation standard of a given country (in terms of currency, date and time, etc.)
|
printf | writes out a set of strings according to a given format
|
sprintf | transforms a set of strings using a format, and returns the resulting string
|
vprintf | prints out the contents of an array as a string presented according to a given format
|
vsprintf | returns the contents of an array as a string presented according to a given format
|
|
Search & replace
|
str_replace | replaces all occurrences of a given search string (str_ireplace is the case-insensitive version)
|
strpbrk | returns the string starting at first occurrence of a character from a given set
|
strpos | returns the position of the first occurrence of a search sequence in a string (stripos: case-insensitive)
|
strrchr | returns the portion of a string starting with the last occurrence of a search sequence
|
strrpos | returns the position of the last occurrence of a search sequence (strripos: case insensitive)
|
strstr | returns the portion of a string starting with the first occurrence of a search sequence (stristr: case insensitive)
|
strtok | returns the next token as delimited by any character of a given set
|
substr | returns a substring defined by its offset and length
|
substr_replace | replaces the text within a portion of a string
|
|
Analysis
|
explode | splits a string into the substrings delimited by a separator, and returns them in an array
|
parse_str | retrieves the parameter names and values from a URL like string
|
str_split | cuts a string into chunks of a given length and returns the result into an array
|
str_word_count | counts the words in a string and returns either their number or the words themselves in an array
|
strcspn | length of the maximum segment at the beginning of a string, free of any of the characters of a given set
|
strlen | returns the length of a string
|
substr_count | returns the number of occurrences of a text sequence within a string
|
|
Construction
|
implode | puts together the substrings contained in an array, joining them by a given character
|
|
Comparison
|
strcmp | string comparison (strcasecmp: case-insensitive)
|
strnatcmp | string comparison using the 'natural order' (strnatcasecmp: case-insensitive)
|
strncmp | comparing the first n characters of two strings (strncasecmp: case-insensitive)
|
substr_compare | compares substrings from two strings
|
|
Transformation
|
addslashes | Add backslashes to escape quotes (single and double) and backslashes -- see also stripslashes
|
str_pad | pads a string on the left, the right or both sides with a given padding string
|
str_repeat | repeats a string a number of times
|
stripslashes | remove the escape backslashes (see: addslashes)
|
strrev | reverse the character order in a string
|
strtolower | converts all characters to lower case
|
strtoupper | converts all characters to upper case
|
strtr | transliterates characters in a string
|
trim | removes white space from both ends of a string (ltrim removes from the left end, rtrim from the right end)
|
ucfirst | converts the first character of the string to upper case
|
ucword | converts the first character of each word to upper case
|
|
HTML
|
htmlentities | replaces the characters undesirable in an HTML code by their entity representation
|
html_entity_decode | converts entity representations in a string into the characters they represent
|
nl2br | inserts <br> line break tags before new line characters, in a string
|
striptags | removes the <br> tags from a string
|
Please refer to the reference manual for more.
Presentation
bin2hex
where:
string | is the string to process
|
|
Returns the hexadecimal representation of the processed string
Reference
chr
where:
ascii | is the ASCII code of a character - in decimal numeration
|
|
Returns the character of the given ASCII code
Reference
echo
echo (string, string, ...) |
where:
string | is a string to write out
|
|
Outputs one or more strings
Reference
fprintf
fprintf (handle, format, list) |
where:
handle | identifies the destination stream -- default: the standard output
| format | is the format to be used
| list | is 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 specifier | one 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-10d | decimal number (d) with a minimum of 10 characters (10), left justified (-), padded with '0' (0)
|
%'*12d | decimal number (d) with a minimum of 12 characters (12), right justified (by default), padded with '*' ('*)
|
%-15s | string 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:
format | has the following contents:
0. | % | the percent sign, to appear as is
| 1. | flags | optional -- 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. | width | minimum 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. | conversion | possible values are:
i | number 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.)
| n | number formatted according to the currency's country format
| % | returns the % character
|
|
|
number | is 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:
float | is the float number to display
|
decimals | optional -- 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_point | character used as the decimal point -- default: . dot
|
thousand_sep | character used to separate groups of 3 digits
|
Returns the float number in the specified format.
Reference
ord
where:
string | the string to be processed
|
|
Returns the ASCII code (in the decimal numeration system) of the first character in the string
Reference
print
where:
string | is the string to write out
|
|
The parentheses may be omitted.
Writes out the specified string.
Reference
printf
printf (format, data_list) |
|
where:
format | is 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_list | is 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:
category | is the information category for which the locale is set. Possible categories are:
LC_ALL | sets locale for all of the below
| LC_COLLATE | sets locale for string comparisons
| LC_CTYPE | sets locale for character ordering
| LC_MONETARY | sets locale for money representation
| LC_NUMERIC | sets locale for number formatting
| LC_TIME | sets locale for time and date formatting
|
|
locale | identifies a country.Example:
en_US | for the USA
| en_UK | for the United Kingdom
| de_DE | for Germany
| fr_FR | for France
| it_IT | for Italy
| jp_JP | for Japan
| etc..
|
|
array | is 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:
format | is the format to use. The format is as described in connection with the fprintf function.
|
data_list | is the comma separated list of data to be converted
|
Returns the specified string presented in the specified format.
Reference
vprintf
where:
format | is the format to use to represent the data in the data list. The format is as described in connection with the fprintf function above.
|
array | is the array to print out
|
Prints out the items of the specified array, as a string presented according to the specified format.
Reference
vprintf
where:
format | is the format to use to represent the data in the data list. The format is as described in connection with the fprintf function above.
|
array | is 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:
search | string to be looked for, or array each item of which is to be looked for -- a string can be considered an one element array
|
replace | string 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.
|
subject | a string or an array to be processed -- when an array each item is processed independently
|
&count | optional -- 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:
string | is the string to process
|
cspn | is a tring containing the tested characters
|
start | optional -- is the offset in the string from which to process; if omitted, the processing starts at the beginning of the string
|
length | optional -- 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:
string | is the string to process
|
charlist | is 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:
string | is the string to be searched
|
search | is the string to be searched for
|
offset | optional -- 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
where:
string | is the string to process
|
search | is 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:
string | is the string to process
|
search | is the sequence to search for
|
offset | optional -- 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
where:
string | is the string to be searched
|
search | is 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
where:
string | string is the string to process
| tokset | is 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:
string | is the string to process
|
offset | is the offset of the substring to return, in the processed string (character at offset included in the result)
|
len | optional -- 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:
string | is the string to process
|
replace | is the replacement text
|
offset | is the offset of the sequence to be replaced
|
len | optional -- 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:
separator | is a string (not a character)
|
string | is the string to explode
|
limit | optional -- 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:
string | is the URL like string to parse for names and values
|
array | optional -- 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
where:
string | is the string to cut up
| len | optional -- 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:
string | is the string to process
|
format | optional -- is an integer that defines how the word count is to be carried out - possible values are:
1 | the words are returned in an array
| 2 | the 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
where:
string | is 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:
string | is the string to be searched
| substr | is the string to be looked for
|
|
Returns the number of occurrences of the substr sequence within the specified string
Reference.
Construction
implode
where:
glue | is the character string to be used to link the imploded elements together
| array | is 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_1 | first string
| string_2 | second string
|
|
The strings string_1 and string_2 are compared bitwise. The result is:
0 | if the strings are equal
|
< 0 | if string_1 is less than string_2
|
> 0 | if 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:
0 | if the strings are equal
|
< 0 | if string_1 is less than string_2
|
> 0 | if string_1 is greater
|
strnatcasecmp is the case-insensitive version of the function.
Reference
strncmp
strncmp (string_1, string_2, n) |
|
where:
string_1 | is the first string
|
string_2 | is the second string
|
n | is the number of characters to compare
|
The first n characters of strings string_1 and string_2 are compared. The result is:
0 | if the strings are equal
|
< 0 | if string_1 is less than string_2
|
> 0 | if 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_1 | is the first string
|
string_2 | is the second string
|
offset | is the offset of the substrings to compare
|
len | is 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:
0 | if the strings are equal
|
< 0 | if string_1 is less than string_2
|
> 0 | if string_1 is greater
|
Reference
Transformation
addslashes
where:
string | is 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:
string | is the string to process
|
len | is the length of the resulting string
|
pad | optional -- is the string to use for padding - default: space
|
mode | optional -- possible values:
STR_PAD_RIGHT | pad on the right (this is the default)
| STR_PAD_LEFT | pad on the left
| STR_PAD_BOTH | pad 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:
string | is the string to repeat
| number | is 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
where:
string | is 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
where:
string | is the string to process
|
|
Returns the string with characters in reversed order
Reference.
strtolower
where:
string | is 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
where:
string | is 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:
string | is the original string to process
|
source | is the string that contains the characters to translate
|
target | is 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.
|
array | is 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
where:
string | is the string to process
|
charlist | optional -- 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
where:
string | is 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
where:
string | is 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:
string | is the string to be converted
|
which_quote | optional -- 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
|
charset | optional -- 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 (&, <, >, etc...) and returns the result (the original string is unmodified)
Reference.
html_entity_decode
html_entity_decode(string, which_quote, charset) |
|
where:
string | is the string to be converted
|
which_quote | optional -- 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
|
charset | optional -- character set to be used -- default: ISO-8859-1
For more, see the reference manual
|
Converts entity representations (&
, <
, >
, "
, etc.) in the string into the characters they represent, and returns the result (the original string is unmodified)
Reference.
nl2br
where:
string | is 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
where:
string | is 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:
checkdate | checks the validity of a Gregorian date given as month, day and year numbers
|
date | returns the date and time in a specified format, for the current time or a given timestamp
|
getdate | returns the date and time elements in an associative array, for the current time or a given timestamp
|
gettimeofday | returns the current time of the day as elapsed seconds since Jan 1st, 1970, and microseconds in the second
|
gmdate | returns GMT date and time in a specified format, for the current time or a given timestamp,
|
gmmktime | returns the timestamp for a GMT date and time given in numeric presentation
|
gmstrftime | returns a formatted string representation of GMT date and time for the current time or a specified timestamp
|
idate | returns one chosen element of date and time (hour, day, etc.) for the current time or a specified timestamp
|
localtime | returns elements of the local time, in an array
|
microtime | returns the current time in seconds and microseconds
|
mktime | returns the timestamp for a local date and time specified in integer representation
|
strftime | returns the date and time in a specified format, for the current local time, or a given local timestamp
|
strtotime | converts a string description of date and time in English, into a timestamp
|
time | returns the current Unix timestamp (number of seconds elapsed since Jan 1st, 1970, 00h 00mn 00s)
|
checkdate
checkdate (month, day, year) |
|
where:
month | an integer month number
|
day | an integer day number
|
year | an integer year number
|
Returns true if the month, day and year represent a valid Gregorian date, false otherwise.
Reference.
date
where:
info | a 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":
a | Lower case am and pm time | am or pm
| A | Upper case AM and PM time | AM or PM
| B | Swatch Internet time | 000 through 999
| c | ISO 8601 date | 2004-11-26T23:15:12+01.00
| d | day of the month, with leading 0 | 01 to 31
| D | day of the week in 3 letters | Mon through Sun
| F | month in full | January through December
| g | 12-hour format without leading 0 | 1 through 12
| G | 24-hour format without leading 0 | 1 though 24
| h | 12-hour format with leading 0 | 01 through 12
| H | 24-hour format with leading 0 | 01 through 24
| i | minutes with leading 0 | 00 through 59
| I | (capital i) daylight saving time | 1: yes, 0: no
| j | day of the month without leading 0 | 1 through 31
| l | (lowercase L) day of the week in full | Monday through Sunday
| L | leap year indication | 1: yes, 0: no
| m | month numeric representation with leading 0 | 01 to 12
| M | month name abbreviation, in 3 letters | Jan through Dec
| n | month numeric representation without leading 0 | 1 to 12
| O | difference to GMT | +0300
| r | RFC2822 formatted | Fri, 26 Nov 2004 00:23:12 +0100
| s | seconds with leading 0 | 00 through 59
| S | English ordinal suffix for day of the month | st, nd, rd, th
| t | number of days in month | 28 through 31
| T | timezone setting | EST,
| U | UNIX timestamp | 2959200
| w | number of the day in the week | 0 for Sunday through 6 for Saturday
| W | ISO 8601 week number in the year | (week starts on Monday)
| y | 2-digit representation of year | 04
| Y | 4-digit representation of year | 2004
| z | day of the year | 0 through 365
| Z | timezone offset in seconds | +3600
|
|
timestamp | opitional -- 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
where:
timestamp | optional -- 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 seconds | 0 through 59
|
"minutes" | Number representation of minutes | 0 through 59
|
"hours" | Number representation of hours | 0 through 23
|
"mday" | Number representation of day of the month | 1 through 31
|
"wday" | Number representation of day of the week | 0 (Sunday) through 6 (saturday)
|
"mon" | Number representation of the month | 1 through 12
|
"year" | Full number of the year | 1970 through 2038
|
"yday" | Number representation of the day of the year | 0 through 365
|
"weekday" | Day of the week in full | Sunday through Saturday
|
"month" | Month name in full | January through December
|
0 | Unix timestamp | Number of seconds elapsed since the Unix Epoch (January 1st, 1970 - 00h 00mn 00s)
|
Reference.
gettimeofday
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
where:
info | is a combination of letters that indicates the informations to return
|
timestamp | optional -- 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:
hour | Number representation of the hour in the day
|
minute | Number representation of the minutes in the hour
|
second | Number representation of the seconds in the minute
|
month | Number representation of the month
|
day | Number representation of the day of the mont
|
year | Number representation of the year
|
dsttime | Daylight 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:
info | is a combination of time information elements that indicates which are returned in the result
|
timestamp | opional -- 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
where:
info | is one character that identifies the information to return. The recognized characters are:
B | Swatch Internet time | 000 through 999
| d | day of the month, with leading 0 | 01 to 31
| h | 12-hour format with leading 0 | 01 through 12
| H | 24-hour format with leading 0 | 01 through 24
| i | minutes with leading 0 | 00 through 59
| I | (capital i) daylight saving time | 1: yes, 0: no
| L | leap year indication | 1: yes, 0: no
| m | month numeric representation with leading 0 | 01 to 31
| s | seconds with leading 0 | 00 through 59
| t | number of days in month | 28 through 31
| U | UNIX timestamp | 2959200
| w | number of the day in the week | 0 for Sunday through 6 for Saturday
| W | ISO 8601 week number in the year | (week starts on Monday)
| y | 2-digit representation of year | 04
| Y | 4-digit representation of year | 2004
| z | day of the year | 0 through 365
| Z | timezone offset in seconds | +3600
|
|
timestamp | optional -- 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:
timestamp | optional -- is the timestamp to process -- if omitted, defaults to the current timestamp as returned by the time function.
|
is_associative | optional -- 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
where:
return_float | optional -- 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:
hour | optional -- is an integer representing the hour
|
minute | optional -- is an integer representing the minute
|
second | optional -- is an integer representing the second
|
month | optional -- is an integer representing the month
|
day | optional -- is an integer representing the day
|
year | optional -- is an integer representing the year
|
isdst | optional -- 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:
info | information list composed of a combination in any desired order of elements selected from the list below:
%a | day of the week abbreviated name in the current locale format
| %A | day of the week full name in the current locale format
| %b | month abbreviated name in the current locale format
| %B | month full name in the current locale format
| %c | date and time in preferred format for current locale
| %C | century number
| %d | day of the month with leading 0 | 01 to 31
| %D | month/ day/ year equivalant to the %m/%d/%y combination
| %e | day of the month, space padded to the left | " 1 " to "31 "
| %g | 2-digit number of the year to which the week pertains, as determined by %V (cf. infra)
| %G | 4-digit number of the year to which the week pertains, as determined by %V (cf. infra)
| %h | same as %b
| %H | time in 24-hour format with leading 0 | 00 through 23
| %I | (capital i) time in 12-hour format with leading 0 | 01 to 12
| %j | day of the year with leading 0 | 001 to 366
| %m | month number with leading 0 | 01 to 12
| %M | minutes | 00 to 59
| %n | new line character
| %p | am or pm time qualification, or corresponding strings in the current locale format
| %r | a.m. or p.m. time qualification
| %R | time in 24-hour notation
| %S | seconds in number representation
| %t | tab character
| %T | current time in the form hh:mn:ss -- equivalent to %H:%M:%S
| %u | day of the week in number representation | 1: Monday to 7:Saturday
| %U | week of the year in number representation | week starts on Sunday -- first week starts on first Sunday
| %V | week of the current year in ISO 8601:1988 representation 01 to 53 | weeks start on Monday -- week 01 is the first that has 4 days or more
| %W | week of the current year number | weeks starts on Monday -- week 01 starts on first monday of the year
| %w | day of the week -- Sunday is day 0
| %x | date without time, in current locale preferred format
| %X | time without date, in current locale preferred format
| %y | year in 2-digit format | 00 through 99
| %Y | year in 4-digit format | Ex: 2004
| %Z | time zone, full name or abbreviation
| %% | a % litteral character
a |
|
timestamp | optional -- Unix timestamp -- if omitted, defaults to the current local timestamp
|
Returns the local time elements as requested by the info argument
Reference.
strtotime
where:
string | is 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
|
array | creates an array
|
array_combine | creates an associative with items from one array as keys, from another as values
|
array_fill | fills a range of numeric keys with a given values
|
array_merge | merges two or more arrays
|
array_merge_recursive | merges two or more arrays recursively, i.e. matching arrays found in the first level arrays are also recursively merged
|
compact | creates an associative array from a list of variables with the variable names as keys
|
range | returns an array containing the elements of a certain ordered set comprised in a specified range
|
|
Array handling
|
array_pop | removes an item from the end of an array and returns its value
|
array_push | adds one or more items to the end of an array
|
array_reduce | applies iteratively a function to the values of an array and returns the value so obtained
|
array_search | searches an array for a given value, and returns the corresponding key
|
array_shift | removes an item from the beginning of an array and returns its value
|
array_sum | returns the sum of the values in an array
|
array_unshift | adds one or more items to the beginning of an array
|
current | returns the current element in an array
|
each | returns the current key and associated value and advances the pointer to the next item
|
end | sets the pointer to the last item
|
extract | creates the variables with the keys from the array as names and their values as values
|
key | returns the current key
|
list | assigns a list of values to a list of variables
|
next | returns the value at the next position and moves the array internal pointer forward
|
prev | returns the value at the previous position and moves the array internal pointer backward
|
reset | resets the pointer to the first element
|
|
Properties
|
array_count_values | returns the number of occurrences of each value found in an array
|
array_key_exists | returns true if a given key is found in the array
|
array_keys | returns the keys found in an array
|
array_values | returns all the values of an array
|
count | counts the elements in an array
|
in_array | tests if a given value is a value contained in the array
|
|
Sorting
|
asort | sorts an associative array on its values, and maintain index association -- arsort sorts in reverse order
|
ksort | sorts an array by keys -- krsort sorts in reverse order
|
natsort | sorts an array using the natural order -- natcasesort case insensitive
|
sort | sorts an array by values and reassigns them numeric keys -- rsort sorts in reverse order
|
uasort | sorts an associative array by value using a user-defines comparison function, maintaining key/value association
|
uksort | sorts an array by key using a user-defined comparison function
|
usort | sorts an array by value using a user-defined comparison function
|
|
Set operations
|
array_chunk | splits an array into smaller arrays with a given number of items
|
array_diff_assoc | compares values with the same key in two array and returns the key/value pairs where difference is found
|
array_diff | returns all key/value pairs of an array that are not found in any of a set of other arrays
|
array_intersec_assoc | returns the key/value pairs of an array found in all of the other arrays from a given set
|
array_intersect | returns the key/value pairs of an array where the value is found in all of the other arrays from a given set
|
|
Transformations
|
array_filter | filters the items of an array, using a callback function
|
array_flip | switches keys and values in an array
|
array_map | derives a new value from each value, using a callback function and returns the key/pair values with the new values
|
array_reverse | returns an array with items in reverse order
|
array_slice | extracts a slice from an array
|
array_splice | removes a portion of an array and replaces it
|
array_unique | returns an array with all duplicates key/value pairs removed
|
array_walk | applies a user function to every item of an array and returns the array so transformed
|
array_walk_recursive | applies 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
where:
key/value | is a key/value pair coded in either of the forms:
key=>value | with an explicit numeric or string key -- key and value within quotes if a string
| value | with 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:
key | is the array the keys are taken from
|
value | is 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:
start | is the numeric starting index
|
number | is the number of items
|
value | is 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_1 | is the first array to be merged
|
array_2 | is 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_1 | is the first array to be merged
|
array_2 | is 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:
$varname | is 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
where:
low | is the lower limit of the range
|
high | is the higher limit of the range
|
step | is 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
where:
array | is 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:
array | is the array to process
|
data_list | is 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:
array | is the array to process
|
callback | is 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:
value | is the data to search for
|
array | is the array to search
|
strict | optional -- 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
where:
array | is 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
where:
array | is 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:
array | is the array to process
|
data | is 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
where:
array | is 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
where:
array | is 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
where:
array | is 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:
array | is the array to process
|
mode | optional -- is the extraction mode which defines how special situations are to be handled
|
prefix | optional -- 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
where:
array | is 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_list | is the comma separated list of the variables to be assigned values
|
array_expression | is 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
where:
array | is 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
where:
array | is 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
where:
array | is 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:
array | is 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:
key | is the key (an integer or a string) to be searched for
|
array | is 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:
array | is the array to process
|
value | optional -- 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
where:
array | is the array to process
| |
The function returns in an array all the values of the array
Reference
count
where:
array | is the array to be processed
|
mode | optional -- 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:
value | is the value to search for
|
array | is the array to search
|
strict | optional -- 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
where:
array | is the associative array to sort
|
flag | optional -- 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
where:
array | is the array to sort
|
flag | optional -- 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
where:
array | is the array to sort
|
flag | optional -- is a flag that select a special mode of sorting. The possible values are:
SORT_REGULAR | values are compared normally -- this is the default
| SORT_NUMERIC | values are compared for their numeric values
| SORT_STRING | values 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
where:
array | is the array to be sorted
|
function | is 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
where:
array | is the array to sort
|
function | is 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:
array | is the array to sort
|
function | is 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:
array | is the array to process
|
size | is the number of items in each resulting chunk
|
preserve_key | optional -- 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:
array | is the array to process
|
array_1 | is 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:
array | is the array to process
|
array_1 | is 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:
array | is the array to process
|
array_1 | is 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:
array | is the array to process
|
array_1 | is 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:
array | is the array to process
|
function | is 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
where:
array | is 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:
function | is the name of the callback function to treat the items of the array to process -- the function name must be enclosed within quotes
|
array | is the original array, to process
|
array_1 | optional -- 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:
array | is the array to process
|
preserve | optional -- 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:
array | is the original array, to process
|
offset | is the numeric index from which to take a slice
|
number | optional -- 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:
array | is the original array to process
|
offset | is the numeric index from which the array items are to be removed
|
number | is the number of items to remove
|
replacement | optional -- 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
where:
array | is 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:
array | is the original array to process
|
callback | is the user callback function which will be automatically scheduled to process each of the item of the original array, and return a value
|
param | optional -- 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:
array | is the original array to process
|
callback | is 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
|
param | optional -- 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
fclose
where:
handle | is 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
where:
handle | is 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
where:
handle | is a handle such as returned by an fopen function, that identifies the file to read
|
length | optional -- 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:
handle | is a handle such as returned by an fopen function, that identifies the file to read
|
length | length is the number of bytes to read, plus 1 (number + 1)µ. If omitted, defaults to 1024.
|
preserved_tags | optional -- 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_uri | is 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 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_uri | is 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_uri | is the URI of the file to process
|
string | is 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_APPEND | append the string to the existing contents of the file (if not present, the string replaces the old contents)
| FILE_USE_INCLUDE | the 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
with no argument
The function flushes all outstanding output files (writes out the buffers and clear them). It returns nothing.
Reference
fopen
where:
file_uri | is the URI that identifies a file
|
mode | is the mode in which the file is to be opened. The possible basic modes are defined by these notations:
r | open 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
| w | open 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
| a | open 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 | x | create 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:
b | the data are treated as binary, i.e. no translation occurs when reading or writing
| t | text 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
where:
handle | is the handle that identify the file to process
|
length | is 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:
handle | is the handle that identify the file to process
|
offset | is the offset of the new position
|
whence | optional -- defines from where the offset is evaluated. The possible values are:
SEEK_SET | the offset is from the beginning of the file -- this is the default
| SEEK_CUR | the offset is from the current position
| SEEK_END | the 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
where:
handle | is 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
where:
handle | is the handle that identify the file to process
|
size | is 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:
handle | is the handle that identifies the file to write to -- in Windows systems, the file must have been opened with the 'b' option
|
string | is the string to write out
|
number | optional -- 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_uri | is the URI which identifies the file to be processed
|
include_option | optional -- 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_name | is the path name to process
|
suffix | optional -- 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
The function returns the directory part of the path name, i.e. with the rightmost component removed.
Reference
file_exists
where:
filename | is 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
where:
file_uri | is the URI of the file to process
| |
The function returns file size, i.e. the number of characters contained in the file.
Reference
filetype
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:
handle | is the file handle which identifies the file to lock
|
| level is the desired protection level:
LOCK_SH | shared (reader) lock
| LOCK_EX | exclusive (write) lock
| LOCK_UN | shared or exclusive lock
| LOCK_NB | non blocking lock
|
|
&block | optional -- 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
The function returns true if the specified URI identifies a directory
Reference
is_executable
The function returns true if the specified URI identifies an executable file
Reference
is_file
The function returns true if the specified URI identifies an existing file
Reference
is_link
The function returns true if the specified URI identifies an existing link
Reference
is_readable
The function returns true if the specified URI identifies a readable file
Reference
is_uploaded_file
The function returns true if the specified URI identifies an uploaded file
Reference
is_writable
The function returns true if the specified URI identifies a writable file
Reference
realpath
where:
relative_uri | is 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_uri | is the URI of an existing file, to be copied
|
dest_uri | is 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
where:
file_uri | is 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
where:
file_uri | is 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
where:
handle | is 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
where:
dir_uri | is the local URI of the directory
|
mod | is a 4-digit octal representation of the permissions on the directory, in the form:
0xyz | where 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_uri | is the URI of the uploaded file to move
|
dest_uri | is 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_uri | is the old URI of the file or directory to rename
|
new_uri | is 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
where:
dir_uri | is 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
where:
file_uri | is 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_uri | is the URI where the file is to be created
| prefix | is 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
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_uri | is the URI of the file to process
|
mtime | optional -- is the modification time; defaults to the current timestamp
|
atime | optional -- 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
where:
file_uri | is 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_uri | is 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
where:
file_uri | is the URI of the file to process.
|
mode | is 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
where:
file_uri | is the URI of the file to process.
|
user | is 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
where:
file_uri | is 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
where:
file_uri | is 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
where:
file_uri | is 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
where:
file_uri | is 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:
floatval | returns the float value of the variable
|
gettype | retuns the type of the variable
|
intval | returns the integer value of the variable
|
is_array | returns true if the variable contains an array
|
is_bool | returns true if the variable contains a booelan
|
is_callable | returns true if the variable contains a callable function
|
is_float | returns true if the variable contains a float
|
is_int | returns true if the variable contains an integer
|
is_null | returns true if the variable contains a null
|
is_numeric | returns true if the variable contains a number
|
is_object | returns true if the variable contains an object
|
is_resource | returns true if the variable contains a resource (as returned by certain functions
|
is_scalar | returns true if the variable contains a scalar
|
is_string | returns true if the variable contains a string
|
isset | returns true if the variable has been assigned a value
|
print_r | displays the type and value of the variable
|
serialize | serializes the variable and returns the serialized value in a string
|
strval | returns the string value of the variable
|
unserialize | restore the original variable from its serialized string
|
unset | strips the variable of its value, making it unset
|
var_dump | displays the type and values of the variable
|
Complete description is to be found in the Reference Manual.
floatval
Syntax:
where:
var_name | is the name of the variable processed by the function.
|
The function returns the float value of the data contained in the variable.
gettype
Syntax:
where:
var_name | is the name of the variable processed by the function.
|
The function returns the type of the data contained in the variable
intval
Syntax:
where:
var_name | is 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:
where:
var_name | is 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:
where:
var_name | is 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:
where:
var_name | is 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:
where:
var_name | is 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:
where:
var_name | is 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:
where:
var_name | is 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:
where:
var_name | is 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:
where:
var_name | is 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:
where:
var_name | is 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:
where:
var_name | is 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:
where:
var_name | is 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:
where:
var_name | is 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:
where:
var_name | is the name of the variable processed by the function.
|
The function displays the type and value(s) of the variable
serialize
Syntax:
where:
var_name | is 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:
where:
var_name | is 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_str | is 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:
where:
var_name | is 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:
where:
var_name | is 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:
The complete description is to be found in the Reference manual
ini_get
where:
var_name | is 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_name | is the name of the configuration directive to query
| value | is 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
where:
category | is 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
where:
seconds | is 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:
constant | returns the value of a named constant
|
define | defines a constant
|
defined | returns true if a constant with the given name has been defined
|
die | terminates the script and displays a message (this is an alias of exit
|
eval | returns the value evaluated by the expression passed as an argument
|
exit | terminates the script and displays a message
|
pack | packs a set of numbers originally presented in an extended form of one octet per digit
|
sleep | delays the execution of the script for a number of seconds
|
time_nanosleep | delays the execution of the script for a number of seconds and nanoseconds
|
unpack | restores a packed set of numbers into its original form
|
usleep | delays 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
where:
expression | is 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
where:
message | is the message to display
|
|
The function terminates the script and displays the specified message
Reference.
die
where:
message | is the message to display
|
|
The function terminates the script and displays the specified message -- this is an alias for exit
Reference.
sleep
where:
seconds | is 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
where:
microseconds | is 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:
seconds | is the number of seconds for which to delay the execution of the script
|
nano | is 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:
name | is the name of the constant to be defined -- uppercase is recommmended -- names starting with 2 underscores ("_") are to be avoided
|
value | is 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
The function returns true if the name is that of a constant, false otherwise.
Reference.
constant
where:
name | is 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
where:
format | is a string of format elements which define how the strings in the list are to be processed.
|
list | is 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:
an | return the first n characters of the string, right padding with NUL
|
An | return the first n characters of the string, right padding with SPACE
|
hn | pack the first n digits, 2 into one octet, lower order nibble first
|
Hn | pack the first n digits, 2 into one octet, higher order nibble first
|
c | pack a number from 0 to 255 into one octet, greater numbers are treated modulo 256
|
C | same as c
|
s | pack a number from 0 to 65535 into 2 octets, greater numbers are treated modulo 65536, in machine dependent order
|
S | same as s
|
v | pack a number from 0 to 65535 into 2 octets, greater numbers are treated modulo 65536, lower order octet first
|
n | pack a number from 0 to 65535 into 2 octets, greater numbers are treated modulo 65536, higher order octet first
|
i | pack an integer into hexadecimal form, with machine dependent number and order of octets
|
I | same as i
|
l | pack a number from 0 to 4294967295 into 4 octets, greater numbers are treated modulo 4294967296, in machine dependent order
|
L | same as l
|
V | pack a number from 0 to 4294967295 into 4 octets, greater numbers are treated modulo 4294967296, lower order octet first
|
N | pack a number from 0 to 4294967295 into 4 octets, greater numbers are treated modulo 4294967296, higher order octet first
|
f | pack a float into its hexadecimal form, with machine dependent octet number and order
|
d | pack 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:
x | add a NUL character to the result string obtained so far, at the position where the element is
|
X | remove one character from the right end of the result string obtained so far
|
@p | adds 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.
an | where:
a | is the format element code, to appear 'as is'
| n | is 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)
|
An | where:
A | is the format element code, to appear 'as is'
| n | is 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)
|
hn | where:
h | is the format element code, to appear 'as is'
| n | is 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'.
|
Hn | where:
H | is the format element code, to appear 'as is'
| n | is 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'.
|
cn | where:
c | (lower case) is the format element code, to appear 'as is'
| n | is 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'.
|
Cn | where:
C | (upper case) is the format element code, to appear 'as is'
| n | is 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).
|
sn | where:
s | is the format element code, to appear 'as is'
| n | is 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.
|
Sn | where:
s | is the format element code, to appear 'as is'
| n | is 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
|
nn | where:
n | the first n -- is the format element code, to appear 'as is'
| n | the 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.
|
vn | where:
n | the first n -- is the format element code, to appear 'as is'
| n | the 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.
|
in | where:
i | is the format element code, to appear 'as is'
| n | is 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
|
In | where:
I | is the format element code, to appear 'as is'
| n | is 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.
|
ln | where:
l | is the format element code, to appear 'as is'
| n | is 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.
|
Ln | where:
L | is the format element code, to appear 'as is'
| n | is 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
|
Nn | where:
N | is the format element code, to appear 'as is'
| n | is 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.
|
Vn | where:
V | is the format element code, to appear 'as is'
| n | is 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.
|
fn | where:
f | is the format element code, to appear 'as is'
| n | is the number of times the format element is to be repeated.
|
Packing a float into its hexadecimal representation.
|
dn | where:
d | is the format element code, to appear 'as is'
| n | is 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):
an | return the first n characters of the string, removing the NULs
|
An | return the first n characters of the string, replacing consecutive SPACEs by one SPACE
|
hn | return the first n digits, 2 from each octet, lower order nibble first -- n rounded to the lower even value
|
Hn | return the first n digits, 2 from each octet, higher order nibble first -- n rounded to the lower even value
|
cn | return the numbers contained in successive octets, signed (value -128 to 127)
|
Cn | return the numbers contained in successive octets, unsigned (value 0 to 255)
|
sn | return the numbers contained in successive octet pairs, interpreted in machine defined octet order, signed (value -32768 to 32767)
|
Sn | return the numbers contained in successive octet pairs, interpreted in machine defined octet order, unsigned (value 0 to 65535)
|
vn | return the numbers contained in successive octet pairs, interpreted in lower order first order, unsigned (value 0 to 65535)
|
nn | return the numbers contained in successive octet pairs, interpreted in higher order first order, unsigned (value 0 to 65535)
|
in | return 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
|
In | return 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
|
ln | return the numbers contained in successive 4-octet groups, interpreted in machine dependent order, signed (value -2147483648 to 2147483647)
|
Ln | return the numbers contained in successive 4-octet groups, interpreted in machine dependent order, unsigned (value 0 to 4294967296)
|
Vn | return the numbers contained in successive 4-octet groups, interpreted in lower order octet first order, signed (value -2147483648 to 2147483647)
|
Nn | return the numbers contained in successive 4-octet groups, interpreted in lower order octet first order, unsigned (value 0 to 4294967296)
|
fn | return the successive float numbers
|
dn | return the successive double numbers
|
Reference.
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_name | is the name you assign to the class
| visible | can take on one of the values:
| property_name | is 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
| value | is the value initially assigned to the property named on the left of the = sign.
| __construct | is the name of the constructor function (always this name, as of PHP 5)
| method_name | is 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:
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:
public | the property can be accessed from anywhere
|
protected | the property can be accessed from the class or one of its extensions
|
private | the 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:
public | the method can be accessed from anywhere (this is the default)
|
protected | the method can be accessed from the class or one of its extensions
|
private | the 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 class | is denoted $this -> property_name
|
- a method of the class | is denoted $this -> method_name
|
|
|
Static members
A static member is declared using the static keyword:
visibility static property_name
| visibility static method_name (...) {
...
}
|
where:
visibility | is the visibility attribute, which can be have one of the values public (this is the default), private, protected
| property_name | is the name of the declared property, which can be assigned a value, as any ordinary property
| method_name | is 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_name | is 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_name | is the name of the class to which the property or method pertains
| property_name | is 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_name | is the name of the declared constant, which is assigned a unmodifiable value
| value | is 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_name | is the name of the class to which the constant pertains
|
property_name | is 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:
$arg | is any name (with the $ sign)
| suffix | is 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_name | is the name you assign to the extended class
| parent_name | is 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_name | for a property
| $this->method_name | for a method
|
| - | properties and methods of the parent class are identified using the parent:: notation:
parent::property_name | for a property
| parent::method_name | for 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_name | is the name you assign to the created object
| class_name | is the name of the class of which the object is to be an instance
| arguments | are the values to be passed as arguments to the constructor function
|
|
Object property access
Syntax:
$object_name -> property_name
Example:
$cylinder -> rad |
 
| object_name | is the name of the object
| property_name | is 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_name | is the name of the object
| method_name | is the name of the method -- the property must have the visibility of public
| arguments | are 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