Memory App
Programming
 




Lower case

array_change_key_case() - Change keys to lower / upper

array_change_key_case($arr); // default CASE_LOWER

array_change_key_case($arr, CASE_UPPER);
(1/9)

Remove duplicates

array_unique() - Remove duplicate values from an array

$arr = array(1, 2, 'b'=>'green', 2);

$arr = array_unique($arr); //  [0] => 1 [1] => 2 [b] => green
(2/9)

Map

array_map() - Same as array_walk (which needs reference) Example 1

function cube($n) 
{
    return pow($n, 3);
}

$a = array(1,2,3);

$b = array_map('cube', $a); // [0] => 1 [1] => 8 [2] => 27
Example 2 (more compact)

$result = array_map(
    create_function(
        '$x', 'return pow($x, 3);'
    ), array(1,2,3));

// [ 1, 8, 27 ]
array_walk() - Apply a user function to every member of an array

$arr = array (1,2,3);

array_walk($arr, create_function('&$x', '$x *= 2;')); // [ 2, 4, 6 ]
(3/9)

Pad

array_pad() - Pad array to the specified length with a value

$array = array(1,2,3);

$result = array_pad($array, 6, 0); // [ 1, 2, 3, 0, 0, 0 ]

echo str_pad(111, 6, 0); // 111000
(4/9)

Replace

array_replace() - Replace elements from passed arrays into the first array

// from PHP 5.3.0

$arr = array('a','b','c');
$arr1 = array(0=>'d');
$arr2 = array(1=>'e');

$result = array_replace($arr, $arr1, $arr2);  // [ d, e, c ]
(5/9)

Extract a slice

array_slice() - Extract a slice of the array

$arr = array(1, 2, 3, 4, 5);

print_r(array_slice($arr, 2)); // [ 3, 4, 5 ]
print_r(array_slice($arr, 0, 2)); // [ 1, 2, 3 ]
print_r(array_slice($arr, -2, 1)); // [0] => 4
print_r(array_slice($arr, -2, 1, true)); // [3] => 4 / preserve keys
(6/9)

Remove a portion

array_splice() - Remove a portion of array and replace it with something else

$arr = array(1, 2, 3, 4, 5);

array_splice($arr, 2); print_r($arr); // [ 1, 2 ]

$arr = array(1, 2, 3, 4, 5);

array_splice($arr, 2, count($arr), array(10,11)); // [ 1, 2, 10, 11 ]
(7/9)

Flip

array_flip() - values became keys

$a = array('a', 'b');

$b = array_flip($a); // [a] => 0 [b] => 1 
(8/9)

Invert the order

array_reverse() - Inverts the order of the array's elements

$a = array('a', 'b');

$b = array_reverse($a); // [0] => b [1] => a


Questions



Top Reference > Programming
0/0 (80)  
Not Logged