php - array_search

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 270. array_search() example
<?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 - array_reverse

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 269. array_reverse() example
<?php
$input
= array("php", 4.0, array("green", "red"));

$result = array_reverse($input);
$result_keyed = array_reverse($input, true);
?> 
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:
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. 

php - array_reduce

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 268. array_reduce() example
<?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 - array_rand

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 267. array_rand() example
<?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 - array_push

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 266. array_push() example
<?php
$stack
= array("orange", "banana");array_push($stack, "apple", "raspberry");print_r($stack);

?> 
The above example will output:
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. 

php - array_pop

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

Example 264. array_pop() example
<?php
$stack
= array("orange", "banana", "apple", "raspberry");

$fruit = array_pop($stack);print_r($stack);
?> 

After this, $stack will have only 3 elements:
Array
(
 [0] => orange
 [1] => banana
 [2] => apple
)
 


and raspberry will be assigned to $fruit.  

php - array_pad

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

Example 263. array_pad() example
<?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 - array_multisort

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 259. Sorting multiple arrays
<?php
$ar1
= array("10", 100, 100, "a");$ar2 = array(1, 3, "2", 1);array_multisort($ar1, $ar2);
var_dump($ar1);var_dump($ar2);

?> 
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.
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 260. Sorting multi-dimensional array
<?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);

?> 
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).
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 261. Sorting database results
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
$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);

?> 
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
// 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);

?> 
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 262. Case insensitive sorting
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
$array
= array('Alpha', 'atomic', 'Beta', 'bank');$array_lowercase = array_map('strtolower', $array);
array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $array);
print_r($array);

?> 
The above example will output:
Array
(
    [0] => Alpha
    [1] => atomic
    [2] => bank
    [3] => Beta
)

php - array_merge_recursive

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

Example 255. array_merge_recursive() example
<?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);

?> 
The above example will output:
Array
(
[color] => Array
(
[favorite] => Array
(
[0] => red
[1] => green
)

[0] => blue
)

[0] => 5
[1] => 10
)

php - array_merge

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 256. array_merge() example
<?php
$array1
= array("color" => "red", 2, 4);$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);$result = array_merge($array1, $array2);print_r($result);

?> 
The above example will output:
Array
(
[color] => green
[0] => 2
[1] => 4
[2] => a
[3] => b
[shape] => trapezoid
[4] => 4
)

Example 257. Simple array_merge() example
<?php
$array1
= array();$array2 = array(1 => "data");$result = array_merge($array1, $array2);

?> 
Don't forget that numeric keys will be renumbered!
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
$array1
= array();$array2 = array(1 => "data");$result = $array1 + $array2;

?> 
The numeric key will be preserved and thus the association remains.
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 258. array_merge() PHP 5 example
<?php
$beginning
= 'foo';$end = array(1 => 'bar');$result = array_merge((array)$beginning, (array)$end);print_r($result);

?> 
The above example will output:
Array
(
[0] => foo
[1] => bar
)