Function Reference

Any problem with PHP can be disscused here
Lixas
Posts: 750
Joined: Wed Feb 16, 2005 4:21 pm

Post by Lixas »

Guys, no need to quote functions references from a web sites. Would be more than enough to post a link to that page :)


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

Post by moslemir »

array_uintersect

(PHP 5)

array_uintersect — Computes the intersection of arrays, compares data by a callback function

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

array_uintersect() returns an array containing all the values of array1 that are present in all the arguments. 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($array1, $array2, "strcasecmp"));
?> [/PHP]
The above example will output:

Code: Select all

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

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_intersect(), array_uintersect_assoc(), array_intersect_uassoc() and array_uintersect_uassoc(). 

--------------------------------------------------------------------------
array_unique

(PHP 4 >= 4.0.1, PHP 5)

array_unique — Removes duplicate values from an array

Description
array array_unique ( array $array )

array_unique() takes input array and returns a new array without duplicate values.

Note that keys are preserved. array_unique() sorts the values treated as string at first, then will keep the first key encountered for every value, and ignore all following keys. It does not mean that the key of the first related value from the unsorted array will be kept.

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

The first element will be used.


Example

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

Code: Select all

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

Example

[PHP]<?php
$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);
?> [/PHP]
The above example will output:

Code: Select all

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

--------------------------------------------------------------------------
array_unshift

(PHP 4, PHP 5)

array_unshift — Prepend one or more elements to the beginning of an array

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

array_unshift() prepends passed elements to the front of the array. Note that the list of elements is prepended as a whole, so that the prepended elements stay in the same order. All numerical array keys will be modified to start counting from zero while literal keys won't be touched.

Returns the new number of elements in the array.


Example

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

Code: Select all

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



See also

Code: Select all

array_shift(), array_push(), and array_pop(). 


--------------------------------------------------------------------------
array_values

(PHP 4, PHP 5)

array_values — Return all the values of an array

Description
array array_values ( array $input )

array_values() returns all the values from the input array and indexes numerically the array.


Example

[PHP]<?php
$array = array("size" => "XL", "color" => "gold");
print_r(array_values($array));
?>[/PHP]
The above example will output:

Code: Select all

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



See also

Code: Select all

array_keys().


--------------------------------------------------------------------------
array_walk_recursive

(PHP 5)

array_walk_recursive — Apply a user function recursively to every member of an array

Description
bool array_walk_recursive ( array &$input, callback $funcname [, mixed $userdata] )

Applies the user-defined function funcname to each element of the input array. This function will recur into deeper arrays. Typically, funcname takes on two parameters. The input parameter's value being the first, and the key/index second. If the optional userdata parameter is supplied, it will be passed as the third parameter to the callback funcname.

Returns TRUE on success or FALSE on failure.

Note: If funcname needs to be working with the actual values of the array, specify the first parameter of funcname as a reference. Then, any changes made to those elements will be made in the original array itself.


Example

[PHP]<?php
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');

function test_print($item, $key)
{
echo "$key holds $item\n";
}

array_walk_recursive($fruits, 'test_print');
?>[/PHP]
The above example will output:

a holds apple
b holds banana
sour holds lemon
You may notice that the key 'sweet' is never displayed. Any key that holds an array will not be passed to the function.


See also

Code: Select all

array_walk(), and information about the callback type. 
----------------------------------------------------
----------------------------
moslemir
Posts: 21
Joined: Sun Mar 18, 2007 12:29 pm
Contact:

Post by moslemir »

array_walk

(PHP 4, PHP 5)

array_walk — Apply a user function to every member of an array

Description
bool array_walk ( array &$array, callback $funcname [, mixed $userdata] )

Returns TRUE on success or FALSE on failure.

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

If function funcname requires more parameters than given to it, an error of level E_WARNING will be generated each time array_walk() calls funcname. These warnings may be suppressed by prepending the PHP error operator @ to the array_walk() call, or by using error_reporting().

Note: If funcname needs to be working with the actual values of the array, specify the first parameter of funcname as a reference. Then, any changes made to those elements will be made in the original array itself.

Note: Passing the key and userdata to funcname was added in 4.0.0

array_walk() is not affected by the internal array pointer of array. array_walk() will walk through the entire array regardless of pointer position.

Users may not change the array itself from the callback function. e.g. Add/delete elements, unset elements, etc. If the array that array_walk() is applied to is changed, the behavior of this function is undefined, and unpredictable.


Example
[PHP]<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");

function test_alter(&$item1, $key, $prefix)
{
$item1 = "$prefix: $item1";
}

function test_print($item2, $key)
{
echo "$key. $item2
\n";
}

echo "Before ...:\n";
array_walk($fruits, 'test_print');

array_walk($fruits, 'test_alter', 'fruit');
echo "... and after:\n";

array_walk($fruits, 'test_print');
?> [/PHP]
The above example will output:

Before ...:
d. lemon
a. orange
b. banana
c. apple
... and after:
d. fruit: lemon
a. fruit: orange
b. fruit: banana
c. fruit: apple



See also

Code: Select all

array_walk_recursive(), create_function(), list(), foreach, each(), call_user_func_array(), and array_map(), and information about the callback type. 


--------------------------------------------------------------------------
array

(PHP 4, PHP 5)

array — Create an array

Description
array array ( [mixed $...] )

Returns an array of the parameters. The parameters can be given an index with the => operator. Read the section on the array type for more information on what an array is.


Note: array() is a language construct used to represent literal arrays, and not a regular function.


Syntax "index => values", separated by commas, define index and values. index may be of type string or integer. When index is omitted, an integer index is automatically generated, starting at 0. If index is an integer, next generated index will be the biggest integer index + 1. Note that when two identical index are defined, the last overwrite the first.

Having a trailing comma after the last defined array entry, while unusual, is a valid syntax.

The following example demonstrates how to create a two-dimensional array, how to specify keys for associative arrays, and how to skip-and-continue numeric indices in normal arrays.

Example

[PHP]<?php
$fruits = array (
"fruits" => array("a" => "orange", "b" => "banana", "c" => "apple"),
"numbers" => array(1, 2, 3, 4, 5, 6),
"holes" => array("first", 5 => "second", "third")
);
?> [/PHP]

Example

[PHP]<?php
$array = array(1, 1, 1, 1, 1, 8 => 1, 4 => 1, 19, 3 => 13);
print_r($array);
?>[/PHP]
The above example will output:

Code: Select all

Array
 (
     [0] => 1
     [1] => 1
     [2] => 1
     [3] => 13
     [4] => 1
     [8] => 1
     [9] => 19
 ) 

Note that index '3' is defined twice, and keep its final value of 13. Index 4 is defined after index 8, and next generated index (value 19) is 9, since biggest index was 8.

This example creates a 1-based array.

Example :. 1-based index with array()

[PHP]<?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>[/PHP]
The above example will output:

Code: Select all

Array
 (
     [1] => January
     [2] => February
     [3] => March
 )

As in Perl, you can access a value from the array inside double quotes. However, with PHP you'll need to enclose your array between curly braces.

Example

[PHP]<?php

$foo = array('bar' => 'baz');
echo "Hello {$foo['bar']}!"; // Hello baz!

?>[/PHP]

See also

Code: Select all

array_pad(), list(), count(), foreach, and range(). 


--------------------------------------------------------------------------
arsort

(PHP 4, PHP 5)

arsort — Sort an array in reverse order and maintain index association

Description
bool arsort ( array &$array [, int $sort_flags] )

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.

Returns TRUE on success or FALSE on failure.

Example

[PHP]<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
arsort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?> [/PHP]
The above example will output:


a = orange
d = lemon
b = banana
c = apple




The fruits have been sorted in reverse alphabetical order, and the index associated with each element has been maintained.

You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().

See also

Code: Select all

asort(), rsort(), ksort(), and sort(). 
----------------------------------------------------
----------------------------
moslemir
Posts: 21
Joined: Sun Mar 18, 2007 12:29 pm
Contact:

Post by moslemir »

asort

(PHP 4, PHP 5)

asort — Sort an array and maintain index association

Description
bool asort ( array &$array [, int $sort_flags] )

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.

Returns TRUE on success or FALSE on failure.

Example

[PHP]<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
asort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?> [/PHP]
The above example will output:


c = apple
b = banana
d = lemon
a = orange




The fruits have been sorted in alphabetical order, and the index associated with each element has been maintained.

You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().

See also

Code: Select all

arsort(), rsort(), ksort(), and sort(). 


--------------------------------------------------------------------------
compact

(PHP 4, PHP 5)

compact — Create array containing variables and their values

Description
array compact ( mixed $varname [, mixed $...] )

compact() takes a variable number of parameters. Each parameter can be either a string containing the name of the variable, or an array of variable names. The array can contain other arrays of variable names inside it; compact() handles it recursively.

For each of these, compact() looks for a variable with that name in the current symbol table and adds it to the output array such that the variable name becomes the key and the contents of the variable become the value for that key. In short, it does the opposite of extract(). It returns the output array with all the variables added to it.

Any strings that are not set will simply be skipped.

Gotcha: Because variable variables may not be used with PHP's Superglobal arrays within functions, the Superglobal arrays may not be passed into compact().


Example

[PHP]<?php
$city = "San Francisco";
$state = "CA";
$event = "SIGGRAPH";

$location_vars = array("city", "state");

$result = compact("event", "nothing_here", $location_vars);
print_r($result);
?> [/PHP]
The above example will output:

Code: Select all

Array
 (
     [event] => SIGGRAPH
     [city] => San Francisco
     [state] => CA
 ) 



See also

Code: Select all

extract(). 


--------------------------------------------------------------------------
count

(PHP 4, PHP 5)

count — Count elements in an array, or properties in an object

Description
int count ( mixed $var [, int $mode] )

Returns the number of elements in var, which is typically an array, since anything else will have one element.

For objects, if you have SPL installed, you can hook into count() by implementing interface Countable. The interface has exactly one method, count(), which returns the return value for the count() function.

If var is not an array or an object with implemented Countable interface, 1 will be returned. There is one exception, if var is NULL, 0 will be returned.

Note: The optional mode parameter is available as of PHP 4.2.0.

If the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array. The default value for mode is 0. count() does not detect infinite recursion.

Caution
count() may return 0 for a variable that isn't set, but it may also return 0 for a variable that has been initialized with an empty array. Use isset() to test if a variable is set.


Please see the Array section of the manual for a detailed explanation of how arrays are implemented and used in PHP.


Example
[PHP]<?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
$result = count($a);
// $result == 3

$b[0] = 7;
$b[5] = 9;
$b[10] = 11;
$result = count($b);
// $result == 3

$result = count(null);
// $result == 0

$result = count(false);
// $result == 1
?> [/PHP]

Example: Recursive count() example (PHP >= 4.2.0)

[PHP]<?php
$food = array('fruits' => array('orange', 'banana', 'apple'),
'veggie' => array('carrot', 'collard', 'pea'));

// recursive count
echo count($food, COUNT_RECURSIVE); // output 8

// normal count
echo count($food); // output 2

?> [/PHP]



See also

Code: Select all

is_array(), isset(), and strlen(). 
----------------------------------------------------
----------------------------
moslemir
Posts: 21
Joined: Sun Mar 18, 2007 12:29 pm
Contact:

Post by moslemir »

current

(PHP 4, PHP 5)

current — Return the current element in an array

Description
mixed current ( array &$array )

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

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

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.


Note: You won't be able to distinguish the end of an array from a boolean FALSE element. To properly traverse an array which may contain FALSE elements, see the each() function.


Example

[PHP]<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport); // $mode = 'bike';
$mode = current($transport); // $mode = 'bike';
$mode = prev($transport); // $mode = 'foot';
$mode = end($transport); // $mode = 'plane';
$mode = current($transport); // $mode = 'plane';
?> [/PHP]

See also

Code: Select all

end(), key(), next(), prev(), reset(), and each(). 

--------------------------------------------------------------------------
each

(PHP 4, PHP 5)

each — Return the current key and value pair from an array and advance the array cursor

Description
array each ( array &$array )

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

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


Example
[PHP]<?php
$foo = array("bob", "fred", "jussi", "jouni", "egon", "marliese");
$bar = each($foo);
print_r($bar);
?> [/PHP]
$bar now contains the following key/value pairs:


Array
(
[1] => bob
[value] => bob
[0] => 0
[key] => 0
)


[PHP]<?php
$foo = array("Robert" => "Bob", "Seppo" => "Sepi");
$bar = each($foo);
print_r($bar);
?>[/PHP]
$bar now contains the following key/value pairs:


Array
(
[1] => Bob
[value] => Bob
[0] => Robert
[key] => Robert
)



each() is typically used in conjunction with list() to traverse an array, here's an example:

Example

[PHP]<?php
$fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');

reset($fruit);
while (list($key, $val) = each($fruit)) {
echo "$key => $val\n";
}
?> [/PHP]
The above example will output:


a => apple
b => banana
c => cranberry





After each() has executed, the array cursor will be left on the next element of the array, or past the last element if it hits the end of the array. You have to use reset() if you want to traverse the array again using each.

Caution
Because assigning an array to another variable resets the original arrays pointer, our example above would cause an endless loop had we assigned $fruit to another variable inside the loop.


See also

Code: Select all

key(), list(), current(), reset(), next(), prev(), and foreach. 


--------------------------------------------------------------------------
end

(PHP 4, PHP 5)

end — Set the internal pointer of an array to its last element

Description
mixed end ( array &$array )

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


Example

[PHP]<?php

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

?>[/PHP]



See also

Code: Select all

current(), each(), prev(), next() and reset(). 
----------------------------------------------------
----------------------------
moslemir
Posts: 21
Joined: Sun Mar 18, 2007 12:29 pm
Contact:

Post by moslemir »

extract

(PHP 4, PHP 5)

extract — Import variables into the current symbol table from an array

Description
int extract ( array $var_array [, int $extract_type [, string $prefix]] )

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

Note: Beginning with version 4.0.5, this function returns the number of variables extracted.

Note: EXTR_IF_EXISTS and EXTR_PREFIX_IF_EXISTS were introduced in version 4.2.0.

Note: EXTR_REFS was introduced in version 4.3.0.

extract() checks each key to see whether it has a valid variable name. It also checks for collisions with existing variables in the symbol table. The way invalid/numeric keys and collisions are treated is determined by the extract_type. It can be one of the following values:

EXTR_OVERWRITE
If there is a collision, overwrite the existing variable.
EXTR_SKIP
If there is a collision, don't overwrite the existing variable.
EXTR_PREFIX_SAME
If there is a collision, prefix the variable name with prefix.
EXTR_PREFIX_ALL
Prefix all variable names with prefix. Beginning with PHP 4.0.5, this includes numeric variables as well.
EXTR_PREFIX_INVALID
Only prefix invalid/numeric variable names with prefix. This flag was added in PHP 4.0.5.
EXTR_IF_EXISTS
Only overwrite the variable if it already exists in the current symbol table, otherwise do nothing. This is useful for defining a list of valid variables and then extracting only those variables you have defined out of $_REQUEST, for example. This flag was added in PHP 4.2.0.
EXTR_PREFIX_IF_EXISTS
Only create prefixed variable names if the non-prefixed version of the same variable exists in the current symbol table. This flag was added in PHP 4.2.0.
EXTR_REFS
Extracts variables as references. This effectively means that the values of the imported variables are still referencing the values of the var_array parameter. You can use this flag on its own or combine it with any other flag by OR'ing the extract_type. This flag was added in PHP 4.3.0.

If extract_type is not specified, it is assumed to be EXTR_OVERWRITE.

Note that prefix is only required if extract_type is EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID or EXTR_PREFIX_IF_EXISTS. If the prefixed result is not a valid variable name, it is not imported into the symbol table. Prefixes are automatically separated from the array key by an underscore character.

extract() returns the number of variables successfully imported into the symbol table.

Warning
Do not use extract() on untrusted data, like user-input ($_GET, ...). If you do, for example, if you want to run old code that relies on register_globals temporarily, make sure you use one of the non-overwriting extract_type values such as EXTR_SKIP and be aware that you should extract in the same order that's defined in variables_order within the php.ini.


A possible use for extract() is to import into the symbol table variables contained in an associative array returned by wddx_deserialize().


Example

[PHP]<?php

/* Suppose that $var_array is an array returned from
wddx_deserialize */

$size = "large";
$var_array = array("color" => "blue",
"size" => "medium",
"shape" => "sphere");
extract($var_array, EXTR_PREFIX_SAME, "wddx");

echo "$color, $size, $shape, $wddx_size\n";

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


blue, large, sphere, medium





The $size wasn't overwritten, because we specified EXTR_PREFIX_SAME, which resulted in $wddx_size being created. If EXTR_SKIP was specified, then $wddx_size wouldn't even have been created. EXTR_OVERWRITE would have caused $size to have value "medium", and EXTR_PREFIX_ALL would result in new variables being named $wddx_color, $wddx_size, and $wddx_shape.

You must use an associative array, a numerically indexed array will not produce results unless you use EXTR_PREFIX_ALL or EXTR_PREFIX_INVALID.

See also

Code: Select all

compact(). 


--------------------------------------------------------------------------
in_array

(PHP 4, PHP 5)

in_array — Checks if a value exists in an array

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

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

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

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

Note: In PHP versions before 4.2.0 needle was not allowed to be an array.


Example

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


Got Irix

Example

[PHP]<?php
$a = array('1.10', 12.4, 1.13);

if (in_array('12.4', $a, true)) {
echo "'12.4' found with strict check\n";
}

if (in_array(1.13, $a, true)) {
echo "1.13 found with strict check\n";
}
?> [/PHP]
The above example will output:


1.13 found with strict check


Example

[PHP]<?php
$a = array(array('p', 'h'), array('p', 'r'), 'o');

if (in_array(array('p', 'h'), $a)) {
echo "'ph' was found\n";
}

if (in_array(array('f', 'i'), $a)) {
echo "'fi' was found\n";
}

if (in_array('o', $a)) {
echo "'o' was found\n";
}
?> [/PHP]
The above example will output:


'ph' was found
'o' was found


See also

Code: Select all

array_search(), array_key_exists(), and isset(). 


--------------------------------------------------------------------------
key

(PHP 4, PHP 5)

key — Fetch a key from an associative array

Description
mixed key ( array &$array )

key() returns the index element of the current array position.


Example
[PHP]<?php
$array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => '****',
'fruit4' => 'apple',
'fruit5' => 'apple');

// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple') {
echo key($array).'
';
}
next($array);
}
?> [/PHP]

See also [PHP]current() and next(). [/PHP]
----------------------------------------------------
----------------------------
moslemir
Posts: 21
Joined: Sun Mar 18, 2007 12:29 pm
Contact:

Post by moslemir »

krsort

(PHP 4, PHP 5)

krsort — Sort an array by key in reverse order

Description
bool krsort ( array &$array [, int $sort_flags] )

Sorts an array by key in reverse order, maintaining key to data correlations. This is useful mainly for associative arrays.

Returns TRUE on success or FALSE on failure.


Example
[PHP]<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
krsort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?> [/PHP]
The above example will output:


d = lemon
c = apple
b = banana
a = orange





You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().

See also

Code: Select all

asort(), arsort(), ksort(), sort(), natsort(), and rsort(). 


--------------------------------------------------------------------------
ksort

(PHP 4, PHP 5)

ksort — Sort an array by key

Description
bool ksort ( array &$array [, int $sort_flags] )

Sorts an array by key, maintaining key to data correlations. This is useful mainly for associative arrays.

Returns TRUE on success or FALSE on failure.


Example

[PHP]<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?> [/PHP]
The above example will output:


a = orange
b = banana
c = apple
d = lemon





You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().

See also

Code: Select all

asort(), arsort(), krsort(), uksort(), sort(), natsort(), and rsort(). 

Note: The second parameter was added in PHP 4.


--------------------------------------------------------------------------
list

(PHP 4, PHP 5)

list — Assign variables as if they were an array

Description
void list ( mixed $varname, mixed $... )

Like array(), this is not really a function, but a language construct. list() is used to assign a list of variables in one operation.

Note: list() only works on numerical arrays and assumes the numerical indices start at 0.


Example

[PHP]<?php

$info = array('coffee', 'brown', 'caffeine');

// Listing all the variables
list($drink, $color, $power) = $info;
echo "$drink is $color and $power makes it special.\n";

// Listing some of them
list($drink, , $power) = $info;
echo "$drink has $power.\n";

// Or let's skip to only the third one
list( , , $power) = $info;
echo "I need $power!\n";

// list() doesn't work with strings
list($bar) = "abcde";
var_dump($bar); // NULL
?> [/PHP]

Example

[PHP]<table>
<tr>
<th>Employee name</th>
<th>Salary</th>
</tr>

<?php

$result = mysql_query("SELECT id, name, salary FROM employees", $conn);
while (list($id, $name, $salary) = mysql_fetch_row($result)) {
echo " <tr>\n" .
" <td><a href=\"info.php?id=$id\">$name</a></td>\n" .
" <td>$salary</td>\n" .
" </tr>\n";
}

?>

</table>
[/PHP]


Warning
list() assigns the values starting with the right-most parameter. If you are using plain variables, you don't have to worry about this. But if you are using arrays with indices you usually expect the order of the indices in the array the same you wrote in the list() from left to right; which it isn't. It's assigned in the reverse order.



Example

[PHP]<?php

$info = array('coffee', 'brown', 'caffeine');

list($a[0], $a[1], $a[2]) = $info;

var_dump($a);

?> [/PHP]
Gives the following output (note the order of the elements compared in which order they were written in the list() syntax):

Code: Select all

array(3) {
   [2]=>
   string(8) "caffeine"
   [1]=>
   string(5) "brown"
   [0]=>
   string(6) "coffee"
 }


See also

Code: Select all

each(), array() and extract(). 
----------------------------------------------------
----------------------------
moslemir
Posts: 21
Joined: Sun Mar 18, 2007 12:29 pm
Contact:

Post by moslemir »

natcasesort

(PHP 4, PHP 5)

natcasesort — Sort an array using a case insensitive "natural order" algorithm

Description
bool natcasesort ( array &$array )

This function implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering".

Returns TRUE on success or FALSE on failure.

natcasesort() is a case insensitive version of natsort().


Example

[PHP]<?php
$array1 = $array2 = array('IMG0.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png');

sort($array1);
echo "Standard sorting\n";
print_r($array1);

natcasesort($array2);
echo "\nNatural order sorting (case-insensitive)\n";
print_r($array2);
?> [/PHP]
The above example will output:


Standard sorting

Code: Select all

Array
 (
     [0] => IMG0.png
     [1] => IMG3.png
     [2] => img1.png
     [3] => img10.png
     [4] => img12.png
     [5] => img2.png
 )

Natural order sorting (case-insensitive)

Code: Select all

Array
 (
     [0] => IMG0.png
     [4] => img1.png
     [3] => img2.png
     [5] => IMG3.png
     [2] => img10.png
     [1] => img12.png
 )


For more information see: Martin Pool's » Natural Order String Comparison page.




See also

Code: Select all

sort(), natsort(), strnatcmp(), and strnatcasecmp(). 


--------------------------------------------------------------------------
natsort

(PHP 4, PHP 5)

natsort — Sort an array using a "natural order" algorithm

Description
bool natsort ( array &$array )

This function implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering". An example of the difference between this algorithm and the regular computer string sorting algorithms (used in sort()) can be seen below:

Returns TRUE on success or FALSE on failure.


Example

[PHP]<?php
$array1 = $array2 = array("img12.png", "img10.png", "img2.png", "img1.png");

sort($array1);
echo "Standard sorting\n";
print_r($array1);

natsort($array2);
echo "\nNatural order sorting\n";
print_r($array2);
?> [/PHP]
The above example will output:


Standard sorting

Code: Select all

Array
 (
     [0] => img1.png
     [1] => img10.png
     [2] => img12.png
     [3] => img2.png
 )

Natural order sorting

Code: Select all

Array
 (
     [3] => img1.png
     [2] => img2.png
     [1] => img10.png
     [0] => img12.png
 )


For more information see: Martin Pool's » Natural Order String Comparison page.




See also

Code: Select all

natcasesort(), strnatcmp(), and strnatcasecmp(). 


--------------------------------------------------------------------------
next

(PHP 4, PHP 5, PECL axis2:0.1.0-0.1.1 xmlreader:1.0-1.0.1)

next — Advance the internal array pointer of an array

Description
mixed next ( array &$array )

Returns the array value in the next place that's pointed to by the internal array pointer, or FALSE if there are no more elements.

next() behaves like current(), with one difference. It advances the internal array pointer one place forward before returning the element value. That means it returns the next array value and advances the internal array pointer by one. If advancing the internal array pointer results in going beyond the end of the element list, next() returns FALSE.

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.


Note: You won't be able to distinguish the end of an array from a boolean FALSE element. To properly traverse an array which may contain FALSE elements, see the each() function.


Example

[PHP]<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport); // $mode = 'bike';
$mode = next($transport); // $mode = 'car';
$mode = prev($transport); // $mode = 'bike';
$mode = end($transport); // $mode = 'plane';
?> [/PHP]

See also

Code: Select all

current(), end(), prev(), reset(), and each(). 
----------------------------------------------------
----------------------------
moslemir
Posts: 21
Joined: Sun Mar 18, 2007 12:29 pm
Contact:

Post by moslemir »

pos

(PHP 4, PHP 5)

pos — Alias of current()

Description
This function is an alias of: current()


--------------------------------------------------------------------------
prev

(PHP 4, PHP 5)

prev — Rewind the internal array pointer

Description
mixed prev ( array &$array )

Returns the array value in the previous place that's pointed to by the internal array pointer, or FALSE if there are no more elements.

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.


Note: You won't be able to distinguish the beginning of an array from a boolean FALSE element. To properly traverse an array which may contain FALSE elements, see the each() function.

prev() behaves just like next(), except it rewinds the internal array pointer one place instead of advancing it.


Example

[PHP]<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport); // $mode = 'bike';
$mode = next($transport); // $mode = 'car';
$mode = prev($transport); // $mode = 'bike';
$mode = end($transport); // $mode = 'plane';
?> [/PHP]



See also

Code: Select all

current(), end(), next(), reset(), and each(). 


--------------------------------------------------------------------------
range
(PHP 4, PHP 5)

range — Create an array containing a range of elements

Description
array range ( mixed $low, mixed $high [, number $step] )

range() returns an array of elements from low to high, inclusive. If low > high, the sequence will be from high to low.

New parameter: The optional step parameter was added in 5.0.0.

If a step value is given, it will be used as the increment between elements in the sequence. step should be given as a positive number. If not specified, step will default to 1.


Example

[PHP]<?php
// array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
foreach (range(0, 12) as $number) {
echo $number;
}

// The step parameter was introduced in 5.0.0
// array(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
foreach (range(0, 100, 10) as $number) {
echo $number;
}

// Use of character sequences introduced in 4.1.0
// array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i');
foreach (range('a', 'i') as $letter) {
echo $letter;
}
// array('c', 'b', 'a');
foreach (range('c', 'a') as $letter) {
echo $letter;
}
?> [/PHP]



Note: Prior to PHP 4.1.0, range() only generated incrementing integer arrays. Support for character sequences and decrementing arrays was added in 4.1.0. Character sequence values are limited to a length of one. If a length greater than one is entered, only the first character is used.

Caution
In PHP versions 4.1.0 through 4.3.2, range() sees numeric strings as strings and not integers. Instead, they will be used for character sequences. For example, "4242" is treated as "4".


See also

Code: Select all

shuffle(), array_fill(), and foreach. 
----------------------------------------------------
----------------------------
moslemir
Posts: 21
Joined: Sun Mar 18, 2007 12:29 pm
Contact:

Post by moslemir »

reset

(PHP 4, PHP 5)

reset — Set the internal pointer of an array to its first element

Description
mixed reset ( array &$array )

reset() rewinds array's internal pointer to the first element and returns the value of the first array element, or FALSE if the array is empty.


Example
[PHP]<?php

$array = array('step one', 'step two', 'step three', 'step four');

// by default, the pointer is on the first element
echo current($array) . "
\n"; // "step one"

// skip two steps
next($array);
next($array);
echo current($array) . "
\n"; // "step three"

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

?> [/PHP]



See also current(), each(), end(), next(), and prev().


--------------------------------------------------------------------------
rsort

(PHP 4, PHP 5)

rsort — Sort an array in reverse order

Description
bool rsort ( array &$array [, int $sort_flags] )

This function sorts an array in reverse order (highest to lowest).

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

Returns TRUE on success or FALSE on failure.


Example

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


0 = orange
1 = lemon
2 = banana
3 = apple





The fruits have been sorted in reverse alphabetical order.

You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().

See also arsort(), asort(), ksort(), krsort(), sort(), and usort().

--------------------------------------------------------------------------
shuffle

(PHP 4, PHP 5)

shuffle — Shuffle an array

Description
bool shuffle ( array &$array )

This function shuffles (randomizes the order of the elements in) an array.

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


Example

[PHP]<?php
$numbers = range(1, 20);
srand((float)microtime() * 1000000);
shuffle($numbers);
foreach ($numbers as $number) {
echo "$number ";
}
?> [/PHP]



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.

See also arsort(), asort(), ksort(), rsort(), sort(), and usort().
----------------------------------------------------
----------------------------
Locked