Function Reference

Any problem with PHP can be disscused here
moslemir
Posts: 21
Joined: Sun Mar 18, 2007 12:29 pm
Contact:

Function Reference (Apache-specific Functions)

Post by moslemir »

apache_child_terminate
(PHP 4 >= 4.0.5, PHP 5)

apache_child_terminate — Terminate apache process after this request

Description
bool apache_child_terminate ( void )

apache_child_terminate() will register the Apache process executing the current PHP request for termination once execution of PHP code it is completed. It may be used to terminate a process after a script with high memory consumption has been run as memory will usually only be freed internally but not given back to the operating system.

Return Values
Returns TRUE if PHP is running as an Apache 1 module, the Apache version is non-multithreaded, and the child_terminate PHP directive is enabled (disabled by default). If these conditions are not met, FALSE is returned and an error of level E_WARNING is generated.

Notes
Note: This function is not implemented on Windows platforms.

See Also
[PHP]exit() [/PHP]

--------------------------------------------------------------------

apache_get_modules


(PHP 4 >= 4.3.2, PHP 5)

apache_get_modules — Get a list of loaded Apache modules

Description
array apache_get_modules ( void )

Get a list of loaded Apache modules.

Return Values
An array of loaded Apache modules.

Examples

[PHP]<?php
print_r(apache_get_modules());
?> [/PHP]
The above example will output something similar to:


[PHP]Array
(
[0] => core
[1] => http_core
[2] => mod_so
[3] => sapi_apache2
[4] => mod_mime
[5] => mod_rewrite
)[/PHP]

--------------------------------------------------------------------
apache_get_version

(PHP 4 >= 4.3.2, PHP 5)

apache_get_version — Fetch Apache version

Description
string apache_get_version ( void )

Fetch the Apache version.

Return Values
Returns the Apache version on success, or FALSE on failure.

Examples

[PHP]<?php
$version = apache_get_version();
echo "$version\n";
?> [/PHP]

The above example will output something similar to:
Apache/1.3.29 (Unix) PHP/4.3.4

See Also
[PHP]phpinfo(); [/PHP]
--------------------------------------------------------------------
apache_getenv
(PHP 4 >= 4.3.0, PHP 5)

apache_getenv — Get an Apache subprocess_env variable

Description
string apache_getenv ( string $variable [, bool $walk_to_top] )

Get an Apache environment variable as specified by variable.

This function requires Apache 2 otherwise it's undefined.

Parameters

variable
The Apache environment variable

walk_to_top
Whether to get the top-level variable available to all Apache layers.


Return Values
The value of the Apache environment variable on success, or FALSE on failure
Examples

The example above shows how to retrieve the value of the Apache environment variable SERVER_ADDR.

[PHP]<?php
$ret = apache_getenv("SERVER_ADDR");
echo $ret;
?>[/PHP]

The above example will output something similar to:

42.24.42.240

See Also
[PHP]apache_setenv()
getenv()
Superglobals[/PHP]

--------------------------------------------------------------------
apache_lookup_uri
(PHP 4, PHP 5)

apache_lookup_uri — Perform a partial request for the specified URI and return all info about it

Description
object apache_lookup_uri ( string $filename )

This performs a partial request for a URI. It goes just far enough to obtain all the important information about the given resource.

This function is only supported when PHP is installed as an Apache module.

Parameters

filename
The filename (URI) that's being requested.


Return Values
An object of related URI information. The properties of this object are:

status
the_request
status_line
method
content_type
handler
uri
filename
path_info
args
boundary
no_cache
no_local_copy
allowed
send_bodyct
bytes_sent
byterange
clength
unparsed_uri
mtime
request_time


Examples


[PHP]<?php
$info = apache_lookup_uri('index.php?var=value');
print_r($info);

if (file_exists($info->filename)) {
echo 'file exists!';
}
?> [/PHP]
The above example will output something similar to:

Code: Select all

stdClass Object
 (
     [status] => 200
     [the_request] => GET /dir/file.php HTTP/1.1
     [method] => GET
     [mtime] => 0
     [clength] => 0
     [chunked] => 0
     [content_type] => application/x-httpd-php
     [no_cache] => 0
     [no_local_copy] => 1
     [unparsed_uri] => /dir/index.php?var=value
     [uri] => /dir/index.php
     [filename] => /home/htdocs/dir/index.php
     [args] => var=value
     [allowed] => 0
     [sent_bodyct] => 0
     [bytes_sent] => 0
     [request_time] => 1074282764
 )
 file exists!
--------------------------------------------------------------------
apache_note
(PHP 4, PHP 5)

apache_note — Get and set apache request notes

Description
string apache_note ( string $note_name [, string $note_value] )

apache_note() is an Apache-specific function which gets and sets values in a request's notes table.

Parameters

note_name
The name of the note.

note_value
The value of the note.


Return Values
If called with one argument, it returns the current value of note note_name. If called with two arguments, it sets the value of note note_name to note_value and returns the previous value of note note_name. If the note cannot be retrieved, FALSE is returned

--------------------------------------------------------------------
apache_request_headers

(PHP 4 >= 4.3.0, PHP 5)

apache_request_headers — Fetch all HTTP request headers

Description
array apache_request_headers ( void )

Fetches all HTTP requests from the current request.

This function is only supported when PHP is installed as an Apache module.

Return Values
An associative array of all the HTTP headers in the current request, or FALSE on failure.

Examples

[PHP]<?php
$headers = apache_request_headers();

foreach ($headers as $header => $value) {
echo "$header: $value
\n";
}
?> [/PHP]
The above example will output something similar to:

Code: Select all

Accept: */*
 Accept-Language: en-us
 Accept-Encoding: gzip, deflate
 User-Agent: Mozilla/4.0
 Host: www.example.com
 Connection: Keep-Alive





Notes
Note: Prior to PHP 4.3.0, apache_request_headers() was called getallheaders(). After PHP 4.3.0, getallheaders() is an alias for apache_request_headers().

Note: You can also get at the value of the common CGI variables by reading them from the environment, which works whether or not you are using PHP as an Apache module. Use phpinfo() to see a list of all of the available environment variables.

Note: As of PHP 4.3.3 you can use this function with the NSAPI server module in Netscape/iPlanet/SunONE webservers, too.

See Also
[PHP]apache_response_headers() [/PHP]
--------------------------------------------------------------------
apache_reset_timeout

(PHP 5 >= 5.1.0)

apache_reset_timeout — Reset the Apache write timer

Description
bool apache_reset_timeout ( void )

apache_reset_timeout() resets the Apache write timer, which defaults to 300 seconds. With set_time_limit(0); ignore_user_abort(true) and periodic apache_reset_timeout() calls, Apache can theoretically run forever.

This function requires Apache 1.

Return Values
Returns TRUE on success or FALSE on failure.

Notes
Note: This function is disabled in safe mode.

--------------------------------------------------------------------
apache_response_headers

(PHP 4 >= 4.3.0, PHP 5)

apache_response_headers — Fetch all HTTP response headers

Description
array apache_response_headers ( void )

Fetch all HTTP response headers.

Return Values
An array of all Apache response headers on success, or FALSE on failure.

Examples

[PHP]<?php
print_r(apache_response_headers());
?> [/PHP]
The above example will output something similar to:

Code: Select all

Array
 (
     [Accept-Ranges] => bytes
     [X-Powered-By] => PHP/4.3.8
 )

Notes
Note: As of PHP 4.3.3 you can use this function with the NSAPI server module in Netscape/iPlanet/SunONE webservers, too.

See Also

[PHP]apache_request_headers()
headers_sent()
[/PHP]
--------------------------------------------------------------------
apache_setenv

(PHP 4 >= 4.2.0, PHP 5)

apache_setenv — Set an Apache subprocess_env variable

Description
bool apache_setenv ( string $variable, string $value [, bool $walk_to_top] )

apache_setenv() sets the value of the Apache environment variable specified by variable.

Note: When setting an Apache environment variable, the corresponding $_SERVER variable is not changed.

Parameters

variable
The environment variable that's being set.

value
The new variable value.

walk_to_top
Whether to set the top-level variable available to all Apache layers.


Return Values
Returns TRUE on success or FALSE on failure.

Examples

[PHP]<?php
apache_setenv("EXAMPLE_VAR", "Example Value");
?>[/PHP]

Notes
Note: apache_setenv() can be paired up with apache_getenv() across separate pages or for setting variables to pass to Server Side Includes (.shtml) that have been included in PHP scripts.

See Also
[PHP]apache_getenv()[/PHP]

--------------------------------------------------------------------
ascii2ebcdic

(No version information available, might be only in CVS)

ascii2ebcdic — Translate string from ASCII to EBCDIC

Description
int ascii2ebcdic ( string $ascii_str )

ascii2ebcdic() is an Apache-specific function which is available only on EBCDIC based operating systems (OS/390, BS2000). It translates the ASCII encoded string ascii_str to its equivalent EBCDIC representation (binary safe), and returns the result.

Parameters

ascii_str
The ASCII string that will be translated.


Return Values
The EBCDIC representation of an ASCII string.

See Also
[PHP]ebcdic2ascii() [/PHP]
--------------------------------------------------------------------
ebcdic2ascii

(No version information available, might be only in CVS)

ebcdic2ascii — Translate string from EBCDIC to ASCII

Description
int ebcdic2ascii ( string $ebcdic_str )

ebcdic2ascii() is an Apache-specific function which is available only on EBCDIC based operating systems (OS/390, BS2000). It translates the EBCDIC encoded string ebcdic_str to its equivalent ASCII representation (binary safe), and returns the result.

Parameters

ebcdic_str
The EBCDIC string that will be translated.


Return Values
The ASCII representation of an EBCDIC string.

See Also

Code: Select all

ascii2ebcdic() 

--------------------------------------------------------------------
getallheaders

(PHP 4, PHP 5)

getallheaders — Fetch all HTTP request headers

Description
array getallheaders ( void )

Fetches all HTTP requests from the current request.

This function is an alias for apache_request_headers(). Please read the apache_request_headers() **** for more information on how this function works.

This function is only supported when PHP is installed as an Apache module.

Return Values
An associative array of all the HTTP headers in the current request, or FALSE on failure.

Notes
Note: As of PHP 4.3.3 you can use this function with the NSAPI server module in Netscape/iPlanet/SunONE webservers, too.

See Also

Code: Select all

apache_response_headers() 

--------------------------------------------------------------------
virtual

(PHP 4, PHP 5)

virtual — Perform an Apache sub-request

Description
bool virtual ( string $filename )

virtual() is an Apache-specific function which is similar to <!--#include virtual...--> in mod_include. It performs an Apache sub-request. It is useful for including CGI scripts or .shtml files, or anything else that you would parse through Apache. Note that for a CGI script, the script must generate valid CGI headers. At the minimum that means it must generate a Content-type header.

To run the sub-request, all buffers are terminated and flushed to the browser, pending headers are sent too.

This function is only supported when PHP is installed as an Apache module.

Parameters

filename
The file that the virtual command will be performed on.


Return Values
Performs the virtual command on success, or returns FALSE on failure.

Notes
Warning
The query string can be passed to the included file but $_GET is copied from the parent script and only $_SERVER['QUERY_STRING'] is filled with the passed query string. The query string may only be passed when using Apache 2. The requested file will not be listed in the Apache access log.


Note: Environment variables set in the requested file are not visible to the calling script.

Note: As of PHP 4.3.3 you can use this function with the NSAPI server module in Netscape/iPlanet/SunONE webservers, too.


----------------------------------------------------
----------------------------
moslemir
Posts: 21
Joined: Sun Mar 18, 2007 12:29 pm
Contact:

Function Reference (Advanced PHP debugger)

Post by moslemir »

apd_breakpoint

(PECL apd:0.2-1.0.1)

apd_breakpoint — Stops the interpreter and waits on a CR from the socket

Description
bool apd_breakpoint ( int $debug_level )

This can be used to stop the running of your script, and await responses on the connected socket. To step the program, just send enter (a blank line), or enter a php command to be executed.

Parameters

debug_level
An integer which is formed by adding together the ****_TRACE constants.

It is not recommended to use MEMORY_TRACE. It is very slow and does not appear to be accurate. ASSIGNMENT_TRACE is not implemented yet.

To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99


Return Values
Returns TRUE on success or FALSE on failure.

Examples

[PHP]bash#tcplisten localhost 7777

APD - Advanced PHP Debugger Trace File
---------------------------------------------------------------------------
Process Pid (6118)
Trace Begun at Sun Mar 10 23:13:12 2002
---------------------------------------------------------------------------
( 0.000000): apd_set_session_trace called at /home/alan/Projects/project2/test.
php:5
( 0.074824): apd_set_session_trace_socket() at /home/alan/Projects/project2/tes
t.php:5 returned. Elapsed (0.074824)
( 0.074918): apd_breakpoint() /home/alan/Projects/project2/test.php:7
++ argv[0] $(??) = 9
apd_breakpoint() at /home/alan/Projects/project2/test.php:7 returned. Elapsed (
-2089521468.1073275368)
>\n
statement: /home/alan/Projects/project2/test.php:8
>\n
statement: /home/alan/Projects/project2/test.php:8
>\n
statement: /home/alan/Projects/project2/test.php:10
>apd_echo($i);
EXEC: apd_echo($i);
0
>apd_echo(serialize(apd_get_active_symbols()));
EXEC: apd_echo(serialize(apd_get_active_symbols()));
a:47:{i:0;s:4:"PWD";i:1;s:10:"COLORFGBG";i:2;s:11:"XAUTHORITY";i:3;s:14:"
COLORTERM_BCE";i:4;s:9:"WINDOWID";i:5;s:14:"ETERM_VERSION";i:6;s:16:"SE
SSION_MANAGER";i:7;s:4:"PS1";i:8;s:11:"GDMSESSION";i:9;s:5:"USER";i:10;s:5:"
MAIL";i:11;s:7:"OLDPWD";i:12;s:5:"LANG";i:13;s:10:"COLORTERM";i:14;s:8:"DISP
LAY";i:15;s:8:"LOGNAME";i:16;s:6:"
>apd_echo(system('ls /home/mydir'));
........
>apd_continue(0);[/PHP]

----------------------------------------------------------------
apd_callstack
(PECL apd:0.2-0.4)

apd_callstack — Returns the current call stack as an array

Description
array apd_callstack ( void )

Returns the current call stack as an array

Return Values
An array containing the current call stack.

Examples

[PHP]<?php
print_r(apd_callstack());
?> [/PHP]

--------------------------------------------------------------------------
apd_clunk

(No version information available, might be only in CVS)

apd_clunk — Throw a warning and a callstack

Description
void apd_clunk ( string $warning [, string $delimiter] )

Behaves like perl's Carp::cluck. Throw a warning and a callstack.

Parameters

warning
The warning to throw.

delimiter
The delimiter. Default to
.


Return Values
No value is returned.

Examples

[PHP]<?php
apd_clunk("Some Warning", "
");
?> [/PHP]

See Also
[PHP]apd_croak()[/PHP]

--------------------------------------------------------------------------
apd_continue

(PECL apd:0.2-1.0.1)

apd_continue — Restarts the interpreter

Description
bool apd_continue ( int $debug_level )

Usually sent via the socket to restart the interpreter.

Parameters

debug_level
An integer which is formed by adding together the ****_TRACE constants.

It is not recommended to use MEMORY_TRACE. It is very slow and does not appear to be accurate. ASSIGNMENT_TRACE is not implemented yet.

To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99


Return Values
Returns TRUE on success or FALSE on failure.

Examples


[PHP]<?php
apd_continue(0);
?> [/PHP]

--------------------------------------------------------------------------
apd_croak
(PECL apd:0.2-0.4)

apd_croak — Throw an error, a callstack and then exit

Description
void apd_croak ( string $warning [, string $delimiter] )

Behaves like perl's Carp::croak. Throw an error, a callstack and then exit.

Parameters

warning
The warning to throw.

delimiter
The delimiter. Default to
.


Return Values
No value is returned.

Examples

[PHP]<?php
apd_croak("Some Warning","<P>");
?> [/PHP]

See Also
[PHP]apd_clunk() [/PHP]

--------------------------------------------------------------------------
apd_dump_function_table

(No version information available, might be only in CVS)

apd_dump_function_table — Outputs the current function table

Description
void apd_dump_function_table ( void )

Outputs the current function table.

Return Values
No value is returned.

Examples

[PHP]<?php
apd_dump_function_table();
?> [/PHP]

--------------------------------------------------------------------------
apd_dump_persistent_resources

(PECL apd:0.2-0.4)

apd_dump_persistent_resources — Return all persistent resources as an array

Description
array apd_dump_persistent_resources ( void )

Return all persistent resources as an array.

Return Values
An array containing the current call stack.

Examples

[PHP]<?php
print_r(apd_dump_persistent_resources());
?>[/PHP]

See Also
[PHP]apd_dump_regular() [/PHP]

--------------------------------------------------------------------------
apd_dump_regular_resources

(PECL apd:0.2-0.4)

apd_dump_regular_resources — Return all current regular resources as an array

Description
array apd_dump_regular_resources ( void )

Return all current regular resources as an array.

Return Values
An array containing the current regular resources.

Examples

[PHP]<?php
print_r(apd_dump_regular_resources());
?> [/PHP]

See Also

Code: Select all

apd_dump_persistent_resources() 

--------------------------------------------------------------------------
apd_echo

(PECL apd:0.2-1.0.1)

apd_echo — Echo to the debugging socket

Description
bool apd_echo ( string $output )

Usually sent via the socket to request information about the running script.

Parameters

output
The debugged variable.


Return Values
Returns TRUE on success or FALSE on failure.

Examples

[PHP]<?php
apd_echo($i);
?> [/PHP]

--------------------------------------------------------------------------
apd_get_active_symbols

(PECL apd:0.2)

apd_get_active_symbols — Get an array of the current variables names in the local scope

Description
array apd_get_active_symbols ( void )

Returns the names of all the variables defined in the active scope, (not their values).

Return Values
A multidimensional array with all the variables.

Examples

[PHP]<?php
apd_echo(apd_get_active_symbols());
?> [/PHP]

--------------------------------------------------------------------------
apd_set_pprof_trace

(PECL apd:0.2-1.0.1)

apd_set_pprof_trace — Starts the session debugging

Description
string apd_set_pprof_trace ( [string $dump_directory [, string $fragment]] )

Starts debugging to pprof_{process_id} in the dump directory.

Parameters

dump_directory
The directory in which the profile dump file is written. If not set, the apd.dumpdir setting from the php.ini file is used.

fragment


Return Values
Returns path of the destination file.

Examples

[PHP]<?php
apd_set_pprof_trace();
?>[/PHP]

See Also
[PHP]apd_set_session_trace() [/PHP]
--------------------------------------------------------------------------
apd_set_session_trace

(PECL apd:0.2-0.4)

apd_set_session_trace — Starts the session debugging

Description
void apd_set_session_trace ( int $debug_level [, string $dump_directory] )

Starts debugging to apd_dump_{process_id} in the dump directory.

Parameters

debug_level
An integer which is formed by adding together the ****_TRACE constants.

It is not recommended to use MEMORY_TRACE. It is very slow and does not appear to be accurate. ASSIGNMENT_TRACE is not implemented yet.

To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99

dump_directory
The directory in which the profile dump file is written. If not set, the apd.dumpdir setting from the php.ini file is used.


Return Values
No value is returned.

Examples

[PHP]<?php
apd_set_session_trace(99);
?> [/PHP]

--------------------------------------------------------------------------
apd_set_session

(PECL apd:0.2-0.4)

apd_set_session — Changes or sets the current debugging level

Description
void apd_set_session ( int $debug_level )

This can be used to increase or decrease debugging in a different area of your application.

Parameters

debug_level
An integer which is formed by adding together the ****_TRACE constants.

It is not recommended to use MEMORY_TRACE. It is very slow and does not appear to be accurate. ASSIGNMENT_TRACE is not implemented yet.

To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99


Return Values
No value is returned.

Examples

[PHP]<?php
apd_set_session(9);
?> [/PHP]

--------------------------------------------------------------------------
apd_set_socket_session_trace

(No version information available, might be only in CVS)

apd_set_socket_session_trace — Starts the remote session debugging

Description
bool apd_set_socket_session_trace ( string $tcp_server, int $socket_type, int $port, int $debug_level )

Connects to the specified tcp_server (eg. tcplisten) and sends debugging data to the socket.

Parameters

tcp_server
IP or Unix Domain socket (like a file) of the TCP server.

socket_type
Can be AF_UNIX for file based sockets or APD_AF_INET for standard tcp/ip.

port
You can use any port, but higher numbers are better as most of the lower numbers may be used by other system services.

debug_level
An integer which is formed by adding together the ****_TRACE constants.

It is not recommended to use MEMORY_TRACE. It is very slow and does not appear to be accurate. ASSIGNMENT_TRACE is not implemented yet.

To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99


Return Values
Returns TRUE on success or FALSE on failure.

Examples

[PHP]<?php
apd_set_socket_session_trace("127.0.0.1",APD_AF_INET,7112,0);
?> [/PHP]

--------------------------------------------------------------------------
override_function

(PECL apd:0.2-1.0.1)

override_function — Overrides built-in functions

Description
bool override_function ( string $function_name, string $function_args, string $function_code )

Overrides built-in functions by replacing them in the symbol table.

Parameters

function_name
The function to override.

function_args
The function arguments, as a coma separated string.

Usually you will want to pass this parameter, as well as the function_code parameter, as a single quote delimited string. The reason for using single quoted strings, is to protect the variable names from parsing, otherwise, if you use double quotes there will be a need to escape the variable names, e.g. \$your_var.

function_code
The new code for the function.


Return Values
Returns TRUE on success or FALSE on failure.

Examples

[PHP]<?php
override_function('test', '$a,$b', 'echo "DOING TEST"; return $a * $b;');
?>[/PHP]

--------------------------------------------------------------------------
rename_function

(PECL apd:0.2-1.0.1)

rename_function — Renames orig_name to new_name in the global function table

Description
bool rename_function ( string $original_name, string $new_name )

Renames a orig_name to new_name in the global function table. Useful for temporarily overriding built-in functions.

Parameters

original_name
The original function name.

new_name
The new name for the original_name function.


Return Values
Returns TRUE on success or FALSE on failure.

Examples

[PHP]<?php
rename_function('mysql_connect', 'debug_mysql_connect' );
?>[/PHP]
----------------------------------------------------
----------------------------
moslemir
Posts: 21
Joined: Sun Mar 18, 2007 12:29 pm
Contact:

Function Reference [Array Functions (1)]

Post by moslemir »

array_change_key_case

(PHP 4 >= 4.2.0, PHP 5)

array_change_key_case — Changes all keys in an array

Description
array array_change_key_case ( array $input [, int $case] )

Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.

Parameters

input
The array to work on

case
Either CASE_UPPER or CASE_LOWER (default)


Return Values
Returns an array with its keys lower or uppercased, or false if input is not an array.

Errors/Exceptions
Throws E_WARNING if input is not an array.

Examples

[PHP]<?php
$input_array = array("FirSt" => 1, "SecOnd" => 4);
print_r(array_change_key_case($input_array, CASE_UPPER));
?> [/PHP]
The above example will output:

Code: Select all

Array
 (
     [FIRST] => 1
     [SECOND] => 4
 )

Notes
Note: If an array has indices that will be the same once run through this function (e.g. "keY" and "kEY"), the value that is later in the array will override other indices
--------------------------------------------------------------------------
array_chunk

(PHP 4 >= 4.2.0, PHP 5)

array_chunk — Split an array into chunks

Description
array array_chunk ( array $input, int $size [, bool $preserve_keys] )

Chunks an array into size large chunks. The last chunk may contain less than size elements.

Parameters

input
The array to work on

size
The size of each chunk

preserve_keys
When set to TRUE keys will be preserved. Default is FALSE which will reindex the chunk numerically


Return Values
Returns a multidimensional numerically indexed array, starting with zero, with each dimension containing size elements.

Errors/Exceptions
If size is less than 1 E_WARNING will be thrown and NULL returned.

Examples

[PHP]<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
print_r(array_chunk($input_array, 2, true));
?> [/PHP]
The above example will output:

Code: Select all

Array
 (
     [0] => Array
         (
             [0] => a
             [1] => b
         )
 
     [1] => Array
         (
             [0] => c
             [1] => d
         )
 
     [2] => Array
         (
             [0] => e
         )
 
 )
 Array
 (
     [0] => Array
         (
             [0] => a
             [1] => b
         )
 
     [1] => Array
         (
             [2] => c
             [3] => d
         )
 
     [2] => Array
         (
             [4] => e
         )
 
 )
--------------------------------------------------------------------------
array_combine

(PHP 5)

array_combine — Creates an array by using one array for keys and another for its values

Description
array array_combine ( array $keys, array $values )

Creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values.

Parameters

keys
Array of keys to be used

values
Array of values to be used


Return Values
Returns the combined array, FALSE if the number of elements for each array isn't equal or if the arrays are empty.

Errors/Exceptions
Throws E_WARNING if keys and values are either empty or the number of elements does not match.

Examples

[PHP]<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);
?>[/PHP]
The above example will output:

Code: Select all

Array
 (
     [green]  => avocado
     [red]    => apple
     [yellow] => banana
 )
 
     
 
 
 
 See Also
 array_merge() 
 array_walk() 
 array_values() 

--------------------------------------------------------------------------
array_count_values

(PHP 4, PHP 5)

array_count_values — Counts all the values of an array

Description
array array_count_values ( array $input )

array_count_values() returns an array using the values of the input array as keys and their frequency in input as values.

Parameters

input
The array of values to count


Return Values
Returns an assosiative array of values from input as keys and their count as value.

Errors/Exceptions
Throws E_WARNING for every element which is not string or integer.

Examples

[PHP]<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>[/PHP]
The above example will output:

Code: Select all

Array
 (
     [1] => 2
     [hello] => 2
     [world] => 1
 )

See Also
[PHP]count()
array_unique()
array_values()
count_chars()[/PHP]
--------------------------------------------------------------------------
array_diff_assoc

(PHP 4 >= 4.3.0, PHP 5)

array_diff_assoc — Computes the difference of arrays with additional index check

Description
array array_diff_assoc ( array $array1, array $array2 [, array $...] )

Compares array1 against array2 and returns the difference. Unlike array_diff() the array keys are used in the comparision.

Parameters

array1
The array to compare from

array2
An array to compare against

...
More arrays to compare against


Return Values
Returns an array containing all the values from array1 that are not present in any of the other arrays.

Examples

In this example you see the "a" => "green" pair is present in both arrays and thus it is not in the ouput from the function. Unlike this, the pair 0 => "red" is in the ouput because in the second argument "red" has key which is 1.

[PHP]<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result = array_diff_assoc($array1, $array2);
print_r($result);
?> [/PHP]
The above example will output:

Code: Select all

Array
 (
     [b] => brown
     [c] => blue
     [0] => red
 )

Example 2. array_diff_assoc() example

Two values from key => value pairs are considered equal only if (string) $elem1 === (string) $elem2 . In other words a strict check takes place so the string representations must be the same.

[PHP]<?php
$array1 = array(0, 1, 2);
$array2 = array("00", "01", "2");
$result = array_diff_assoc($array1, $array2);
print_r($result);
?> [/PHP]
The above example will output:

Code: Select all

Array
 (
     [0] => 0
     [1] => 1
     )


Notes
Note: This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_diff_assoc($array1[0], $array2[0]);.

See Also
[PHP]array_diff()
array_intersect()
array_intersect_assoc() [/PHP]

--------------------------------------------------------------------------
array_diff_key

(PHP 5 >= 5.1.0)

array_diff_key — Computes the difference of arrays using keys for comparison

Description
array array_diff_key ( array $array1, array $array2 [, array $...] )

Compares the keys from array1 against the keys from array2 and returns the difference. This function is like array_diff() except the comparison is done on the keys instead of the values.

Parameters

array1
The array to compare from

array2
An array to compare against

...
More arrays to compare against


Return Values
Returns an array containing all the entries from array1 that are not present in any of the other arrays.

Examples

The two keys from the key => value pairs are considered equal only if (string) $key1 === (string) $key2 . In other words a strict type check is executed so the string representation must be the same.

[PHP]<?php
$array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan' => 8);

var_dump(array_diff_key($array1, $array2));
?> [/PHP]
The above example will output:

Code: Select all

array(2) {
   ["red"]=>
   int(2)
   ["purple"]=>
   int(4)
 }

Notes
Note: This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff_key($array1[0], $array2[0]);.

See Also
array_diff()
array_udiff()
array_diff_assoc()
array_diff_uassoc()
array_udiff_assoc()
array_udiff_uassoc()
array_diff_ukey()
array_intersect()
array_intersect_assoc()
array_intersect_uassoc()
array_intersect_key()
array_intersect_ukey()
--------------------------------------------------------------------------
array_diff_uassoc

(PHP 5)

array_diff_uassoc — Computes the difference of arrays with additional index check which is performed by a user supplied callback function

Description
array array_diff_uassoc ( array $array1, array $array2 [, array $..., callback $key_compare_func] )

Compares array1 against array2 and returns the difference. Unlike array_diff() the array keys are used in the comparision.

Unlike array_diff_assoc() an user supplied callback function is used for the indices comparision, not internal function.

Parameters

array1
The array to compare from

array2
An array to compare against

...
More arrays to compare against

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


Return Values
Returns an array containing all the entries from array1 that are not present in any of the other arrays.

Examples

The "a" => "green" pair is present in both arrays and thus it is not in the ouput from the function. Unlike this, the pair 0 => "red" is in the ouput because in the second argument "red" has key which is 1.

[PHP]<?php
function key_compare_func($a, $b)
{
if ($a === $b) {
return 0;
}
return ($a > $b)? 1:-1;
}

$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result = array_diff_uassoc($array1, $array2, "key_compare_func");
print_r($result);
?> [/PHP]
The above example will output:

Code: Select all

Array
 (
     [b] => brown
     [c] => blue
     [0] => red
 )
 

The equality of 2 indices is checked by the user supplied callback function.

Notes
Note: This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_diff_uassoc($array1[0], $array2[0], "key_compare_func");.

See Also
array_diff()
array_diff_assoc()
array_udiff()
array_udiff_assoc()
array_udiff_uassoc()
array_intersect()
array_intersect_assoc()
array_uintersect()
array_uintersect_assoc()
array_uintersect_uassoc()

--------------------------------------------------------------------------
array_diff_ukey

(PHP 5 >= 5.1.0)

array_diff_ukey — Computes the difference of arrays using a callback function on the keys for comparison

Description
array array_diff_ukey ( array $array1, array $array2 [, array $ ..., callback $key_compare_func] )

Compares the keys from array1 against the keys from array2 and returns the difference. This function is like array_diff() except the comparison is done on the keys instead of the values.

Unlike array_diff_key() an user supplied callback function is used for the indices comparision, not internal function.

Parameters

array1
The array to compare from

array2
An array to compare against

...
More arrays to compare against

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


Return Values
Returns an array containing all the entries from array1 that are not present in any of the other arrays.

Examples

[PHP]<?php
function key_compare_func($key1, $key2)
{
if ($key1 == $key2)
return 0;
else if ($key1 > $key2)
return 1;
else
return -1;
}

$array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan' => 8);

var_dump(array_diff_ukey($array1, $array2, 'key_compare_func'));
?>[/PHP]
The above example will output:

Code: Select all

array(2) {
   ["red"]=>
   int(2)
   ["purple"]=>
   int(4)
 }

Notes
Note: This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff_ukey($array1[0], $array2[0], 'callback_func');.

See Also
array_diff()
array_udiff()
array_diff_assoc()
array_diff_uassoc()
array_udiff_assoc()
array_udiff_uassoc()
array_diff_key()
array_intersect()
array_intersect_assoc()
array_intersect_uassoc()
array_intersect_key()
array_intersect_ukey()
--------------------------------------------------------------------------
array_diff

(PHP 4 >= 4.0.1, PHP 5)

array_diff — Computes the difference of arrays

Description
array array_diff ( array $array1, array $array2 [, array $ ...] )

Compares array1 against array2 and returns the difference.

Examples

[PHP]<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result);
?>[/PHP]
Multiple occurrences in $array1 are all treated the same way. This will output :

Array
(
[1] => blue
)

Notes
Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.

Note: This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff($array1[0], $array2[0]);.

Warning
This was broken in PHP 4.0.4!


See Also
array_diff_assoc()
array_intersect()
array_intersect_assoc()
--------------------------------------------------------------------------
array_fill_keys

(PHP 5 >= 5.2.0)

array_fill_keys — Fill an array with values, specifying keys

Description
array array_fill_keys ( array $keys, mixed $value )

Fills an array with the value of the value parameter, using the values of the keys array as keys.

Parameters

keys
Array of values that will be used as keys

value
Either an string or an array of values


Return Values
Returns the filled array

Examples

[PHP]<?php
$keys = array('foo', 5, 10, 'bar');
$a = array_fill_keys($keys, 'banana');
print_r($a);
?> [/PHP]
The above example will output:

Code: Select all

Array
 (
     [foo] => banana
     [5] => banana
     [10] => banana
     [bar] => banana
 )

See Also

Code: Select all

array_fill() 
 array_combine() 

--------------------------------------------------------------------------
array_fill

(PHP 4 >= 4.2.0, PHP 5)

array_fill — Fill an array with values

Description
array array_fill ( int $start_index, int $num, mixed $value )

Fills an array with num entries of the value of the value parameter, keys starting at the start_index parameter.

Parameters

start_index
The first index of the returned array

num
Number of elements to insert

value
Values to use filling


Return Values
Returns the filled array

Errors/Exceptions
Throws a E_WARNING if num is less than one.

Examples

[PHP]<?php
$a = array_fill(5, 6, 'banana');
print_r($a);
?>[/PHP]
The above example will output:

Code: Select all

Array
 (
     [5]  => banana
     [6]  => banana
     [7]  => banana
     [8]  => banana
     [9]  => banana
     [10] => banana
 )

See Also

Code: Select all

str_repeat() 
 range()
----------------------------------------------------
----------------------------
moslemir
Posts: 21
Joined: Sun Mar 18, 2007 12:29 pm
Contact:

Function Reference [Array Functions (2)]

Post by moslemir »

array_filter

(PHP 4 >= 4.0.6, PHP 5)

array_filter — Filters elements of an array using a callback function

Description
array array_filter ( array $input [, callback $callback] )

Iterates over each value in the input array passing them to the callback function. If the callback function returns true, the current value from input is returned into the result array. Array keys are preserved.

Parameters

input
The array to iterate over

callback
The callback function to use

If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed.


Return Values
Returns the filtered array.

Examples



[PHP]<?php
function odd($var)
{
return($var & 1);
}

function even($var)
{
return(!($var & 1));
}

$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array(6, 7, 8, 9, 10, 11, 12);

echo "Odd :\n";
print_r(array_filter($array1, "odd"));
echo "Even:\n";
print_r(array_filter($array2, "even"));
?> [/PHP]
The above example will output:

Code: Select all

Odd :
 Array
 (
     [a] => 1
     [c] => 3
     [e] => 5
 )
 Even:
 Array
 (
     [0] => 6
     [2] => 8
     [4] => 10
     [6] => 12
 ) 
 


[PHP]<?php

$entry = array(
0 => 'foo',
1 => false,
2 => -1,
3 => null,
4 => ''
);

print_r(array_filter($entry));
?> [/PHP]
The above example will output:

Code: Select all

Array
 (
     [0] => foo
     [2] => -1
 )

Notes
Caution
If the array is changed from the callback function (e.g. element added, deleted or unset) the behavior of this function is undefined.


See Also

Code: Select all

array_map() 
 array_reduce() 
 array_walk() 
--------------------------------------------------------------------------
array_flip

(PHP 4, PHP 5)

array_flip — Exchanges all keys with their associated values in an array

Description
array array_flip ( array $trans )

array_flip() returns an array in flip order, i.e. keys from trans become values and values from trans become keys.

Note that the values of trans need to be valid keys, i.e. they need to be either integer or string. A warning will be emitted if a value has the wrong type, and the key/value pair in question will not be flipped.

If a value has several occurrences, the latest key will be used as its values, and all others will be lost.

Parameters

trans
An array of key/value pairs to be flipped.


Return Values
Returns the flipped array on success and FALSE on failure.

Examples

[PHP]<?php
$trans = array_flip($trans);
$original = strtr($str, $trans);
?> [/PHP]


[PHP]<?php
$trans = array("a" => 1, "b" => 1, "c" => 2);
$trans = array_flip($trans);
print_r($trans);
?> [/PHP]
now $trans is:

Code: Select all

Array
 (
     [1] => b
     [2] => c
 )
 

See Also

Code: Select all

array_values() 
 array_keys() 
 array_reverse() 

--------------------------------------------------------------------------
array_intersect_assoc

(PHP 4 >= 4.3.0, PHP 5)

array_intersect_assoc — Computes the intersection of arrays with additional index check

Description
array array_intersect_assoc ( array $array1, array $array2 [, array $ ...] )

array_intersect_assoc() returns an array containing all the values of array1 that are present in all the arguments. Note that the keys are used in the comparison unlike in array_intersect().

Parameters

array1
The array with master values to check.

array2
An array to compare values against.

array
A variable list of arrays to compare.


Return Values
Returns an associative array containing all the values in array1 that are present in all of the arguments.

Examples

[PHP]<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result_array = array_intersect_assoc($array1, $array2);
print_r($result_array);
?>[/PHP]
The above example will output:

Code: Select all

Array
 (
     [a] => green
 )
 

In our example you see that only the pair "a" => "green" is present in both arrays and thus is returned. The value "red" is not returned because in $array1 its key is 0 while the key of "red" in $array2 is 1.

The two values from the key => value pairs are considered equal only if (string) $elem1 === (string) $elem2 . In other words a strict type check is executed so the string representation must be the same.

See Also

Code: Select all

array_intersect() 
 array_uintersect_assoc() 
 array_intersect_uassoc() 
 array_uintersect_uassoc() 
 array_diff() 
 array_diff_assoc() 

--------------------------------------------------------------------------
array_intersect_key

(PHP 5 >= 5.1.0)

array_intersect_key — Computes the intersection of arrays using keys for comparison

Description
array array_intersect_key ( array $array1, array $array2 [, array $ ...] )

array_intersect_key() returns an array containing all the values of array1 which have matching keys that are present in all the arguments.

Parameters

array1
The array with master keys to check.

array2
An array to compare keys against.

array
A variable list of arrays to compare.


Return Values
Returns an associative array containing all the values of array1 which have matching keys that are present in all arguments.

Examples

[PHP]<?php
$array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan' => 8);

var_dump(array_intersect_key($array1, $array2));
?> [/PHP]
The above example will output:

Code: Select all

array(2) {
   ["blue"]=>
   int(1)
   ["green"]=>
   int(3)
 }

In our example you see that only the keys 'blue' and 'green' are present in both arrays and thus returned. Also notice that the values for the keys 'blue' and 'green' differ between the two arrays. A match still occurs because only the keys are checked. The values returned are those of array1.

The two keys from the key => value pairs are considered equal only if (string) $key1 === (string) $key2 . In other words a strict type check is executed so the string representation must be the same.

See Also

Code: Select all

array_diff() 
 array_udiff() 
 array_diff_assoc() 
 array_diff_uassoc() 
 array_udiff_assoc() 
 array_udiff_uassoc() 
 array_diff_key() 
 array_diff_ukey() 
 array_intersect() 
 array_intersect_assoc() 
 array_intersect_uassoc() 
 array_intersect_ukey() 

--------------------------------------------------------------------------
array_intersect_uassoc

(PHP 5)

array_intersect_uassoc — Computes the intersection of arrays with additional index check, compares indexes by a callback function

Description
array array_intersect_uassoc ( array $array1, array $array2 [, array $ ..., callback $key_compare_func] )

array_intersect_uassoc() returns an array containing all the values of array1 that are present in all the arguments. Note that the keys are used in the comparison unlike in array_intersect().

The index comparison is done by a user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Parameters

array1
Initial array for comparision of the arrays.

array2
First array to compare keys against.

array
Variable list of array arguments to compare values against.

key_compare_func
User supplied callback function to do the comparision.


Return Values
Returns the values of array1 whose values exist in all of the arguments.

Examples

[PHP]<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_intersect_uassoc($array1, $array2, "strcasecmp"));
?> [/PHP]
The above example will output:

Code: Select all

Array
 (
     [b] => brown
 )

See Also

Code: Select all

array_intersect() 
 array_intersect_assoc() 
 array_uintersect_assoc() 
 array_uintersect_uassoc() 
 array_intersect_key() 
 array_intersect_ukey() 

--------------------------------------------------------------------------
array_intersect_ukey

(PHP 5 >= 5.1.0)

array_intersect_ukey — Computes the intersection of arrays using a callback function on the keys for comparison

Description
array array_intersect_ukey ( array $array1, array $array2 [, array $..., callback $key_compare_func] )

array_intersect_ukey() returns an array containing all the values of array1 which have matching keys that are present in all the arguments.

This comparison is done by a user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first key is considered to be respectively less than, equal to, or greater than the second.

Parameters

array1
Initial array for comparision of the arrays.

array2
First array to compare keys against.

array
Variable list of array arguments to compare keys against.

key_compare_func
User supplied callback function to do the comparision.


Return Values
Returns the values of array1 whose keys exist in all the arguments.

Examples

[PHP]<?php
function key_compare_func($key1, $key2)
{
if ($key1 == $key2)
return 0;
else if ($key1 > $key2)
return 1;
else
return -1;
}

$array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan' => 8);

var_dump(array_intersect_ukey($array1, $array2, 'key_compare_func'));
?> [/PHP]
The above example will output:

Code: Select all

array(2) {
   ["blue"]=>
   int(1)
   ["green"]=>
   int(3)
 }

In our example you see that only the keys 'blue' and 'green' are present in both arrays and thus returned. Also notice that the values for the keys 'blue' and 'green' differ between the two arrays. A match still occurs because only the keys are checked. The values returned are those of array1.

See Also

Code: Select all

array_diff() 
 array_udiff() 
 array_diff_assoc() 
 array_diff_uassoc() 
 array_udiff_assoc() 
 array_udiff_uassoc() 
 array_diff_key() 
 array_diff_ukey() 
 array_intersect() 
 array_intersect_assoc() 
 array_intersect_uassoc() 
 array_intersect_key() 
 

--------------------------------------------------------------------------
array_intersect

(PHP 4 >= 4.0.1, PHP 5)

array_intersect — Computes the intersection of arrays

Description
array array_intersect ( array $array1, array $array2 [, array $ ...] )

array_intersect() returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.

Parameters

array1
The array with master values to check.

array2
An array to compare values against.

array
A variable list of arrays to compare.


Return Values
Returns an array containing all of the values in array1 whose values exist in all of the parameters.

Examples

[PHP]<?php
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);
?> [/PHP]
The above example will output:

Code: Select all

Array
 (
     [a] => green
     [0] => red
 )




Notes
Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.

See Also

Code: Select all

array_intersect_assoc() 
 array_diff() 
 array_diff_assoc() 

--------------------------------------------------------------------------
array_key_exists

(PHP 4 >= 4.0.7, PHP 5)

array_key_exists — Checks if the given key or index exists in the array

Description
bool array_key_exists ( mixed $key, array $search )

array_key_exists() returns TRUE if the given key is set in the array. key can be any value possible for an array index. array_key_exists() also works on objects.

Parameters

key
Value to check.

search
An array with keys to check.


Return Values
Returns TRUE on success or FALSE on failure.

Examples


[PHP]<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
echo "The 'first' element is in the array";
}
?>[/PHP]

Note: The name of this function is key_exists() in PHP 4.0.6.

Other Examples
isset() does not return TRUE for array keys that correspond to a NULL value, while array_key_exists() does.

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

// returns false
isset($search_array['first']);

// returns true
array_key_exists('first', $search_array);
?> [/PHP]


See Also

Code: Select all

isset() 
 array_keys() 
 in_array() 

--------------------------------------------------------------------------
array_keys

(PHP 4, PHP 5)

array_keys — Return all the keys of an array

Description
array array_keys ( array $input [, mixed $search_value [, bool $strict]] )

array_keys() returns the keys, numeric and string, from the input array.

If the optional search_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the input are returned. As of PHP 5, you can use strict parameter for comparison including type (===).

Parameters

input
An array containing keys to return.

search_value
If specified, then only keys containing these values are returned.

strict
As of PHP 5, this parameter determines if strict comparision (===) should be used during the search.


Return Values
Returns an array of all the keys in input.

Examples

[PHP]<?php
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));

$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));

$array = array("color" => array("blue", "red", "green"),
"size" => array("small", "medium", "large"));
print_r(array_keys($array));
?> [/PHP]
The above example will output:

Code: Select all

Array
 (
     [0] => 0
     [1] => color
 )
 Array
 (
     [0] => 0
     [1] => 3
     [2] => 4
 )
 Array
 (
     [0] => color
     [1] => size
 )

See Also

Code: Select all

array_values() 
 array_key_exists() 

--------------------------------------------------------------------------
array_map

(PHP 4 >= 4.0.6, PHP 5)

array_map — Applies the callback to the elements of the given arrays

Description
array array_map ( callback $callback, array $arr1 [, array $...] )

array_map() returns an array containing all the elements of arr1 after applying the callback function to each one. The number of parameters that the callback function accepts should match the number of arrays passed to the array_map()

Parameters

callback
Callback function to run for each element in each array.

arr1
An array to run through the callback function.

array
Variable list of array arguments to run through the callback function.


Return Values
Returns an array containing all the elements of arr1 after applying the callback function to each one.

Examples

[PHP]<?php
function cube($n)
{
return($n * $n * $n);
}

$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
?> [/PHP]
This makes $b have:

Code: Select all

Array
 (
     [0] => 1
     [1] => 8
     [2] => 27
     [3] => 64
     [4] => 125
 )

Examples

[PHP]<?php
function show_Spanish($n, $m)
{
return("The number $n is called $m in Spanish");
}

function map_Spanish($n, $m)
{
return(array($n => $m));
}

$a = array(1, 2, 3, 4, 5);
$b = array("uno", "dos", "tres", "cuatro", "cinco");

$c = array_map("show_Spanish", $a, $b);
print_r($c);

$d = array_map("map_Spanish", $a , $b);
print_r($d);
?> [/PHP]
The above example will output:

Code: Select all

// printout of $c
 Array
 (
     [0] => The number 1 is called uno in Spanish
     [1] => The number 2 is called dos in Spanish
     [2] => The number 3 is called tres in Spanish
     [3] => The number 4 is called cuatro in Spanish
     [4] => The number 5 is called cinco in Spanish
 )
 
 // printout of $d
 Array
 (
     [0] => Array
         (
             [1] => uno
         )
 
     [1] => Array
         (
             [2] => dos
         )
 
     [2] => Array
         (
             [3] => tres
         )
 
     [3] => Array
         (
             [4] => cuatro
         )
 
     [4] => Array
         (
             [5] => cinco
         )
 
 )


Usually when using two or more arrays, they should be of equal length because the callback function is applied in parallel to the corresponding elements. If the arrays are of unequal length, the shortest one will be extended with empty elements.

An interesting use of this function is to construct an array of arrays, which can be easily performed by using NULL as the name of the callback function

[PHP]<?php
$a = array(1, 2, 3, 4, 5);
$b = array("one", "two", "three", "four", "five");
$c = array("uno", "dos", "tres", "cuatro", "cinco");

$d = array_map(null, $a, $b, $c);
print_r($d);
?> [/PHP]
The above example will output:

Code: Select all

Array
 (
     [0] => Array
         (
             [0] => 1
             [1] => one
             [2] => uno
         )
 
     [1] => Array
         (
             [0] => 2
             [1] => two
             [2] => dos
         )
 
     [2] => Array
         (
             [0] => 3
             [1] => three
             [2] => tres
         )
 
     [3] => Array
         (
             [0] => 4
             [1] => four
             [2] => cuatro
         )
 
     [4] => Array
         (
             [0] => 5
             [1] => five
             [2] => cinco
         )
 
 )

See Also

Code: Select all

array_filter() 
 array_reduce() 
 array_walk() 
 create_function()
 
----------------------------------------------------
----------------------------
moslemir
Posts: 21
Joined: Sun Mar 18, 2007 12:29 pm
Contact:

Post by moslemir »

array_merge_recursive

(PHP 4 >= 4.0.1, PHP 5)

array_merge_recursive — Merge two or more arrays recursively

Description
array array_merge_recursive ( array $array1 [, array $...] )

array_merge_recursive() merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

If the input arrays have the same string keys, then the values for these keys are merged together into an array, and this is done recursively, so that if one of the values is an array itself, the function will merge it with a corresponding entry in another array too. If, however, the arrays have the same numeric key, the later value will not overwrite the original value, but will be appended.

Parameters

array1
Initial array to merge.

array
Variable list of arrays to recursively merge.


Return Values
An array of values resulted from merging the arguments together.

Examples

[PHP]<?php
$ar1 = array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);
print_r($result);
?> [/PHP]
The above example will output:

Code: Select all

Array
 (
     [color] => Array
         (
             [favorite] => Array
                 (
                     [0] => red
                     [1] => green
                 )
 
             [0] => blue
         )
 
     [0] => 5
     [1] => 10
 ) 
 


See Also
[PHP]array_merge() [/PHP]

--------------------------------------------------------------------------
array_merge

(PHP 4, PHP 5)

array_merge — Merge one or more arrays

Description
array array_merge ( array $array1 [, array $array2 [, array $...]] )

array_merge() merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

If only one array is given and the array is numerically indexed, the keys get reindexed in a continuous way.


Example

[PHP]<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "****", 4);
$result = array_merge($array1, $array2);
print_r($result);
?> [/PHP]
The above example will output:

Code: Select all

Array
 (
     [color] => green
     [0] => 2
     [1] => 4
     [2] => a
     [3] => b
     [shape] => ****
     [4] => 4
 ) 

example

[PHP]<?php
$array1 = array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);
?> [/PHP]
Don't forget that numeric keys will be renumbered!

Code: Select all

Array
 (
     [0] => data
 ) 
If you want to completely preserve the arrays and just want to append them to each other (not overwriting the previous keys), use the + operator:

[PHP]<?php
$array1 = array();
$array2 = array(1 => "data");
$result = $array1 + $array2;
?> [/PHP]
The numeric key will be preserved and thus the association remains.

Code: Select all

Array
 (
     [1] => data
 ) 



Warning
The behavior of array_merge() was modified in PHP 5. Unlike PHP 4, array_merge() now only accepts parameters of type array. However, you can use typecasting to merge other types. See the example below for details.


example

[PHP]<?php
$beginning = 'foo';
$end = array(1 => 'bar');
$result = array_merge((array)$beginning, (array)$end);
print_r($result);
?> [/PHP]
The above example will output:

Code: Select all

Array
 (
     [0] => foo
     [1] => bar
 ) 



See also

Code: Select all

array_merge_recursive(), array_combine() and array operators. 

--------------------------------------------------------------------------
array_multisort

(PHP 4, PHP 5)

array_multisort — Sort multiple or multi-dimensional arrays

Description
bool array_multisort ( array $ar1 [, mixed $arg [, mixed $... [, array $...]]] )

Returns TRUE on success or FALSE on failure.

array_multisort() can be used to sort several arrays at once, or a multi-dimensional array by one or more dimensions.

Associative (string) keys will be maintained, but numeric keys will be re-indexed.

The input arrays are treated as columns of a table to be sorted by rows - this resembles the functionality of SQL ORDER BY clause. The first array is the primary one to sort by. The rows (values) in that array that compare the same are sorted by the next input array, and so on.

The argument structure of this function is a bit unusual, but flexible. The first argument has to be an array. Subsequently, each argument can be either an array or a sorting flag from the following lists.

Sorting order flags:

SORT_ASC - Sort in ascending order
SORT_DESC - Sort in descending order

Sorting type flags:

SORT_REGULAR - Compare items normally
SORT_NUMERIC - Compare items numerically
SORT_STRING - Compare items as strings

No two sorting flags of the same type can be specified after each array. The sorting flags specified after an array argument apply only to that array - they are reset to default SORT_ASC and SORT_REGULAR before each new array argument.


Example

[PHP]<?php
$ar1 = array("10", 100, 100, "a");
$ar2 = array(1, 3, "2", 1);
array_multisort($ar1, $ar2);

var_dump($ar1);
var_dump($ar2);
?> [/PHP]
In this example, after sorting, the first array will contain "10", "a", 100, 100. The second array will contain 1, 1, "2", 3. The entries in the second array corresponding to the identical entries in the first array (100 and 100) were sorted as well.

Code: Select all

array(4) {
   [0]=> string(2) "10"
   [1]=> string(1) "a"
   [2]=> int(100)
   [3]=> int(100)
 }
 array(4) {
   [0]=> int(1)
   [1]=> int(1)
   [2]=> string(1) "2"
   [3]=> int(3)
 }

Example

[PHP]<?php
$ar = array(
array("10", 11, 100, 100, "a"),
array( 1, 2, "2", 3, 1)
);
array_multisort($ar[0], SORT_ASC, SORT_STRING,
$ar[1], SORT_NUMERIC, SORT_DESC);
var_dump($ar);
?> [/PHP]
In this example, after sorting, the first array will transform to "10", 100, 100, 11, "a" (it was sorted as strings in ascending order). The second will contain 1, 3, "2", 2, 1 (sorted as numbers, in descending order).

Code: Select all

array(2) {
   [0]=> array(5) {
     [0]=> string(2) "10"
     [1]=> int(100)
     [2]=> int(100)
     [3]=> int(11)
     [4]=> string(1) "a"
   }
   [1]=> array(5) {
     [0]=> int(1)
     [1]=> int(3)
     [2]=> string(1) "2"
     [3]=> int(2)
     [4]=> int(1)
   }
 }

Example

For this example, each element in the data array represents one row in a table. This type of dataset is typical of database records.

Example data:


volume | edition
-------+--------
67 | 2
86 | 1
85 | 6
98 | 2
86 | 6
67 | 7


The data as an array, called data. This would usually, for example, be obtained by looping with mysql_fetch_assoc().

[PHP]<?php
$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);
?> [/PHP]
In this example, we will order by volume descending, edition ascending.

We have an array of rows, but array_multisort() requires an array of columns, so we use the below code to obtain the columns, then perform the sorting.

[PHP]<?php
// Obtain a list of columns
foreach ($data as $key => $row) {
$volume[$key] = $row['volume'];
$edition[$key] = $row['edition'];
}

// Sort the data with volume descending, edition ascending
// Add $data as the last parameter, to sort by the common key
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
?>[/PHP]
The dataset is now sorted, and will look like this:


volume | edition
-------+--------
98 | 2
86 | 1
86 | 6
85 | 6
67 | 2
67 | 7






Example

Both SORT_STRING and SORT_REGULAR are case sensitive, strings starting with a capital letter will come before strings starting with a lowercase letter.

To perform a case insensitive search, force the sorting order to be determined by a lowercase copy of the original array.

[PHP]<?php
$array = array('Alpha', 'atomic', 'Beta', 'bank');
$array_lowercase = array_map('strtolower', $array);

array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $array);

print_r($array);
?> [/PHP]
The above example will output:

Code: Select all

Array
 (
     [0] => Alpha
     [1] => atomic
     [2] => bank
     [3] => Beta
 )

--------------------------------------------------------------------------
array_pad

(PHP 4, PHP 5)

array_pad — Pad array to the specified length with a value

Description
array array_pad ( array $input, int $pad_size, mixed $pad_value )

array_pad() returns a copy of the input padded to size specified by pad_size with value pad_value. If pad_size is positive then the array is padded on the right, if it's negative then on the left. If the absolute value of pad_size is less than or equal to the length of the input then no padding takes place. It is possible to add most 1048576 elements at a time.

Parameters

input
Initial array of values to pad.

pad_size
New size of the array.

pad_value
Value to pad if input is less than pad_size.


Return Values
Returns a copy of the input padded to size specified by pad_size with value pad_value. If pad_size is positive then the array is padded on the right, if it's negative then on the left. If the absolute value of pad_size is less than or equal to the length of the input then no padding takes place.

Examples

[PHP]<?php
$input = array(12, 10, 9);

$result = array_pad($input, 5, 0);
// result is array(12, 10, 9, 0, 0)

$result = array_pad($input, -7, -1);
// result is array(-1, -1, -1, -1, 12, 10, 9)

$result = array_pad($input, 2, "noop");
// not padded
?> [/PHP]



See Also
[PHP]array_fill()
range() [/PHP]

--------------------------------------------------------------------------
array_pop

(PHP 4, PHP 5)

array_pop — Pop the element off the end of array

Description
mixed array_pop ( array &$array )

array_pop() pops and returns the last value of the array, shortening the array by one element. If array is empty (or is not an array), NULL will be returned.

Note: This function will reset() the array pointer after use.

Parameters

array
The array to get the value from.


Return Values
Returns the last value of array. If array is empty (or is not an array), NULL will be returned.

Examples

[PHP]<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_pop($stack);
print_r($stack);
?> [/PHP]
After this, $stack will have only 3 elements:

Array

Code: Select all

(
     [0] => orange
     [1] => banana
     [2] => apple
 ) 
and raspberry will be assigned to $fruit.

See Also

Code: Select all

See also array_push(), array_shift(), and array_unshift().
----------------------------------------------------
----------------------------
moslemir
Posts: 21
Joined: Sun Mar 18, 2007 12:29 pm
Contact:

Post by moslemir »

array_product

(PHP 5 >= 5.1.0)

array_product — Calculate the product of values in an array

Description
number array_product ( array $array )

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


Example

[PHP]<?php

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

?>[/PHP]
The above example will output:


product(a) = 384
--------------------------------------------------------------------------
array_push

(PHP 4, PHP 5)

array_push — Push one or more elements onto the end of array

Description
int array_push ( array &$array, mixed $var [, mixed $...] )

array_push() treats array as a stack, and pushes the passed variables onto the end of array. The length of array increases by the number of variables pushed. Has the same effect as: <?php
$array[] = $var;
?> repeated for each var.

Returns the new number of elements in the array.


Example

[PHP]<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
?> [/PHP]
The above example will output:

Code: Select all

Array
 (
     [0] => orange
     [1] => banana
     [2] => apple
     [3] => raspberry
 ) 



Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.

Note: array_push() will raise a warning if the first argument is not an array. This differs from the $var[] behaviour where a new array is created.

See also array_pop(), array_shift(), and array_unshift().


--------------------------------------------------------------------------
array_rand

(PHP 4, PHP 5)

array_rand — Pick one or more random entries out of an array

Description
mixed array_rand ( array $input [, int $num_req] )

array_rand() is rather useful when you want to pick one or more random entries out of an array. It takes an input array and an optional argument num_req which specifies how many entries you want to pick - if not specified, it defaults to 1.

If you are picking only one entry, array_rand() returns the key for a random entry. Otherwise, it returns an array of keys for the random entries. This is done so that you can pick random keys as well as values out of the array.

Note: As of PHP 4.2.0, there is no need to seed the random number generator with srand() or mt_srand() as this is now done automatically.


Example

[PHP]<?php
srand((float) microtime() * 10000000);
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";
?> [/PHP]



See also

Code: Select all

shuffle(). 

--------------------------------------------------------------------------
array_reduce

(PHP 4 >= 4.0.5, PHP 5)

array_reduce — Iteratively reduce the array to a single value using a callback function

Description
mixed array_reduce ( array $input, callback $function [, int $initial] )

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


Example

[PHP]<?php
function rsum($v, $w)
{
$v += $w;
return $v;
}

function rmul($v, $w)
{
$v *= $w;
return $v;
}

$a = array(1, 2, 3, 4, 5);
$x = array();
$b = array_reduce($a, "rsum");
$c = array_reduce($a, "rmul", 10);
$d = array_reduce($x, "rsum", 1);
?> [/PHP]



This will result in $b containing 15, $c containing 1200 (= 10*1*2*3*4*5), and $d containing 1.

See also

Code: Select all

array_filter(), array_map(), array_unique(), and array_count_values(). 

--------------------------------------------------------------------------
array_reverse

(PHP 4, PHP 5)

array_reverse — Return an array with elements in reverse order

Description
array array_reverse ( array $array [, bool $preserve_keys] )

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


Example

[PHP]<?php
$input = array("php", 4.0, array("green", "red"));
$result = array_reverse($input);
$result_keyed = array_reverse($input, true);
?> [/PHP]
This makes both $result and $result_keyed have the same elements, but note the difference between the keys. The printout of $result and $result_keyed will be:

Code: Select all

Array
 (
     [0] => Array
         (
             [0] => green
             [1] => red
         )
 
     [1] => 4
     [2] => php
 )
 Array
 (
     [2] => Array
         (
             [0] => green
             [1] => red
         )
 
     [1] => 4
     [0] => php
 )

Note: The second parameter was added in PHP 4.0.3.

See also array_flip().
----------------------------------------------------
----------------------------
moslemir
Posts: 21
Joined: Sun Mar 18, 2007 12:29 pm
Contact:

Post by moslemir »

array_search

(PHP 4 >= 4.0.5, PHP 5)

array_search — Searches the array for a given value and returns the corresponding key if successful

Description
mixed array_search ( mixed $needle, array $haystack [, bool $strict] )

Searches haystack for needle and returns the key if it is found in the array, FALSE otherwise.

Note: If needle is a string, the comparison is done in a case-sensitive manner.

Note: Prior to PHP 4.2.0, array_search() returns NULL on failure instead of FALSE.

If the optional third parameter strict is set to TRUE then the array_search() will also check the types of the needle in the haystack.

If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.


Example

[PHP]<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>[/PHP]



Warning
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.


See also

Code: Select all

array_keys(), array_values(), array_key_exists(), and in_array().

--------------------------------------------------------------------------
array_shift

(PHP 4, PHP 5)

array_shift — Shift an element off the beginning of array

Description
mixed array_shift ( array &$array )

array_shift() shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. All numerical array keys will be modified to start counting from zero while literal keys won't be touched. If array is empty (or is not an array), NULL will be returned.

Note: This function will reset() the array pointer after use.

Example

[PHP]<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack);
?> [/PHP]
This would result in $stack having 3 elements left:

Code: Select all

Array
 (
     [0] => banana
     [1] => apple
     [2] => raspberry
 )

and orange will be assigned to $fruit.



See also array_unshift(), array_push(), and array_pop().

--------------------------------------------------------------------------
array_slice

(PHP 4, PHP 5)

array_slice — Extract a slice of the array

Description
array array_slice ( array $array, int $offset [, int $length [, bool $preserve_keys]] )

array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters.

If offset is non-negative, the sequence will start at that offset in the array. If offset is negative, the sequence will start that far from the end of the array.

If length is given and is positive, then the sequence will have that many elements in it. If length is given and is negative then the sequence will stop that many elements from the end of the array. If it is omitted, then the sequence will have everything from offset up until the end of the array.

Note that array_slice() will reorder and reset the array indices by default. Since PHP 5.0.2, you can change this behaviour by setting preserve_keys to TRUE.


Example

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

$output = array_slice($input, 2); // returns "c", "d", and "e"
$output = array_slice($input, -2, 1); // returns "d"
$output = array_slice($input, 0, 3); // returns "a", "b", and "c"

// note the differences in the array keys
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));
?> [/PHP]
The above example will output:

Code: Select all

Array
 (
     [0] => c
     [1] => d
 )
 Array
 (
     [2] => c
     [3] => d
 )

See also

Code: Select all

array_splice() and unset(). 


--------------------------------------------------------------------------
array_splice

(PHP 4, PHP 5)

array_splice — Remove a portion of the array and replace it with something else

Description
array array_splice ( array &$input, int $offset [, int $length [, array $replacement]] )

array_splice() removes the elements designated by offset and length from the input array, and replaces them with the elements of the replacement array, if supplied. It returns an array containing the extracted elements. Note that numeric keys in input are not preserved.

If offset is positive then the start of removed portion is at that offset from the beginning of the input array. If offset is negative then it starts that far from the end of the input array.

If length is omitted, removes everything from offset to the end of the array. If length is specified and is positive, then that many elements will be removed. If length is specified and is negative then the end of the removed portion will be that many elements from the end of the array. Tip: to remove everything from offset to the end of the array when replacement is also specified, use count($input) for length.

If replacement array is specified, then the removed elements are replaced with elements from this array. If offset and length are such that nothing is removed, then the elements from the replacement array are inserted in the place specified by the offset. Note that keys in replacement array are not preserved. If replacement is just one element it is not necessary to put array() around it, unless the element is an array itself.

The following statements change the values of $input the same way:

Table 21. array_splice() equivalents

[PHP]array_push($input, $x, $y) array_splice($input, count($input), 0, array($x, $y))
array_pop($input) array_splice($input, -1)
array_shift($input) array_splice($input, 0, 1)
array_unshift($input, $x, $y) array_splice($input, 0, 0, array($x, $y))
$input[$x] = $y // for arrays where key equals offset array_splice($input, $x, 1, $y)[/PHP]

Returns the array consisting of removed elements.


Example

[PHP]<?php
$input = array("red", "green", "blue", "yellow");
array_splice($input, 2);
// $input is now array("red", "green")

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

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, count($input), "orange");
// $input is now array("red", "orange")

$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));
// $input is now array("red", "green",
// "blue", "black", "maroon")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 3, 0, "purple");
// $input is now array("red", "green",
// "blue", "purple", "yellow");
?>[/PHP]

See also

Code: Select all

array_slice(), unset(), and array_merge()

--------------------------------------------------------------------------
array_sum

(PHP 4 >= 4.0.4, PHP 5)

array_sum — Calculate the sum of values in an array

Description
number array_sum ( array $array )

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


Example

[PHP]<?php
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";

$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4);
echo "sum(b) = " . array_sum($b) . "\n";
?>[/PHP]
The above example will output:

sum(a) = 20
sum(b) = 6.9

Note: PHP versions prior to 4.2.1 modified the passed array itself and converted strings to numbers (which most of the time converted them to zero, depending on their value).
----------------------------------------------------
----------------------------
Tails5
Posts: 1302
Joined: Wed Mar 15, 2006 8:09 am
Contact:

Post by Tails5 »

Helpful to have it here, but I think that's from the PHP.net ****...
Webmaster Yoda: You must confront the cPanel. Then, and only then, a webmaster will you be.
Julius Caesar: Veni, vidi, posti
moslemir
Posts: 21
Joined: Sun Mar 18, 2007 12:29 pm
Contact:

Post by moslemir »

array_udiff_assoc

(PHP 5)

array_udiff_assoc — Computes the difference of arrays with additional index check, compares data by a callback function

Description
array array_udiff_assoc ( array $array1, array $array2 [, array $ ..., callback $data_compare_func] )

array_udiff_assoc() returns an array containing all the values from array1 that are not present in any of the other arguments. Note that the keys are used in the comparison unlike array_diff() and array_udiff(). The comparison of arrays' data is performed by using an user-supplied callback. In this aspect the behaviour is opposite to the behaviour of array_diff_assoc() which uses internal function for comparison.


Example

[PHP]<?php
class cr {
private $priv_member;
function cr($val)
{
$this->priv_member = $val;
}

function comp_func_cr($a, $b)
{
if ($a->priv_member === $b->priv_member) return 0;
return ($a->priv_member > $b->priv_member)? 1:-1;
}
}

$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);

$result = array_udiff_assoc($a, $b, array("cr", "comp_func_cr"));
print_r($result);
?> [/PHP]
The above example will output:

Code: Select all

Array
 (
     [0.1] => cr Object
         (
             [priv_member:private] => 9
         )
 
     [0.5] => cr Object
         (
             [priv_member:private] => 12
         )
 
     [0] => cr Object
         (
             [priv_member:private] => 23
         )
 )

In our example above you see the "1" => new cr(4) pair is present in both arrays and thus it is not in the ouput from the function.

For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Note: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_udiff_assoc($array1[0], $array2[0], "some_comparison_func");.

See also array_diff(), array_diff_assoc(), array_diff_uassoc(), array_udiff(), array_udiff_uassoc(), array_intersect(), array_intersect_assoc(), array_uintersect(), array_uintersect_assoc() and array_uintersect_uassoc().

--------------------------------------------------------------------------
array_udiff_uassoc

(PHP 5)

array_udiff_uassoc — Computes the difference of arrays with additional index check, compares data and indexes by a callback function

Description
array array_udiff_uassoc ( array $array1, array $array2 [, array $ ..., callback $data_compare_func, callback $key_compare_func] )

array_udiff_uassoc() returns an array containing all the values from array1 that are not present in any of the other arguments. Note that the keys are used in the comparison unlike array_diff() and array_udiff(). The comparison of arrays' data is performed by using an user-supplied callback : data_compare_func. In this aspect the behaviour is opposite to the behaviour of array_diff_assoc() which uses internal function for comparison. The comparison of keys (indices) is done also by the callback function key_compare_func. This behaviour is unlike what array_udiff_assoc() does, since the latter compares the indices by using an internal function.

Example

[PHP]<?php
class cr {
private $priv_member;
function cr($val)
{
$this->priv_member = $val;
}

function comp_func_cr($a, $b)
{
if ($a->priv_member === $b->priv_member) return 0;
return ($a->priv_member > $b->priv_member)? 1:-1;
}

function comp_func_key($a, $b)
{
if ($a === $b) return 0;
return ($a > $b)? 1:-1;
}
}
$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);

$result = array_udiff_uassoc($a, $b, array("cr", "comp_func_cr"), array("cr", "comp_func_key"));
print_r($result);
?>[/PHP]
The above example will output:

Code: Select all

Array
 (
     [0.1] => cr Object
         (
             [priv_member:private] => 9
         )
 
     [0.5] => cr Object
         (
             [priv_member:private] => 12
         )
 
     [0] => cr Object
         (
             [priv_member:private] => 23
         )
 )

In our example above you see the "1" => new cr(4) pair is present in both arrays and thus it is not in the ouput from the function. Keep in mind that you have to supply 2 callback functions.

For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Note: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_udiff_uassoc($array1[0], $array2[0], "data_compare_func", "key_compare_func");.

See also array_diff(), array_diff_assoc(), array_diff_uassoc(), array_udiff(), array_udiff_assoc(), array_intersect(), array_intersect_assoc(), array_uintersect(), array_uintersect_assoc() and array_uintersect_uassoc().
--------------------------------------------------------------------------
array_udiff

(PHP 5)

array_udiff — Computes the difference of arrays by using a callback function for data comparison

Description
array array_udiff ( array $array1, array $array2 [, array $ ..., callback $data_compare_func] )

array_udiff() returns an array containing all the values of array1 that are not present in any of the other arguments. Note that keys are preserved. For the comparison of the data data_compare_func is used. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. This is unlike array_diff() which uses an internal function for comparing the data.

Example

[PHP]<?php
class cr {
private $priv_member;
function cr($val)
{
$this->priv_member = $val;
}

function comp_func_cr($a, $b)
{
if ($a->priv_member === $b->priv_member) return 0;
return ($a->priv_member > $b->priv_member)? 1:-1;
}
}
$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);

$result = array_udiff($a, $b, array("cr", "comp_func_cr"));
print_r($result);
?> [/PHP]
The above example will output:

Code: Select all

Array
 (
     [0.5] => cr Object
         (
             [priv_member:private] => 12
         )
 
     [0] => cr Object
         (
             [priv_member:private] => 23
         )
 
 )

Note: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_udiff($array1[0], $array2[0], "data_compare_func");.

See also

Code: Select all

array_diff(), array_diff_assoc(), array_diff_uassoc(), array_udiff_assoc(), array_udiff_uassoc(), array_intersect(), array_intersect_assoc(), array_uintersect(), array_uintersect_assoc() and array_uintersect_uassoc().


--------------------------------------------------------------------------
array_uintersect_assoc

(PHP 5)

array_uintersect_assoc — Computes the intersection of arrays with additional index check, compares data by a callback function

Description
array array_uintersect_assoc ( array $array1, array $array2 [, array $ ..., callback $data_compare_func] )

array_uintersect_assoc() returns an array containing all the values of array1 that are present in all the arguments. Note that the keys are used in the comparison unlike in array_uintersect(). The data is compared by using a callback function.


Example

[PHP]<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_uintersect_assoc($array1, $array2, "strcasecmp"));
?> [/PHP]
The above example will output:

Code: Select all

Array
 (
     [a] => green
 )

For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

See also

Code: Select all

array_uintersect(), array_intersect_assoc(), array_intersect_uassoc() and array_uintersect_uassoc().

--------------------------------------------------------------------------
array_uintersect_uassoc

(PHP 5)

array_uintersect_uassoc — Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions

Description
array array_uintersect_uassoc ( array $array1, array $array2 [, array $ ..., callback $data_compare_func, callback $key_compare_func] )

array_uintersect_uassoc() returns an array containing all the values of array1 that are present in all the arguments. Note that the keys are used in the comparison unlike in array_uintersect(). Both the data and the indexes are compared by using separate callback functions.


Example

[PHP]<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_uintersect_uassoc($array1, $array2, "strcasecmp", "strcasecmp"));
?>[/PHP]
The above example will output:

Code: Select all

Array
 (
     [a] => green
     [b] => brown
 )

For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

See also

Code: Select all

array_uintersect(), array_intersect_assoc(), array_intersect_uassoc() and array_uintersect_assoc().
----------------------------------------------------
----------------------------
delivi
Posts: 454
Joined: Sun Mar 26, 2006 1:24 pm
Contact:

Post by delivi »

wow great reference, thanks for sharing :)
Locked