PHP

  minte9
REMEMBERS




Last update:   07-02-2022

Duplicates

array_unique() - Remove duplicate values from an array
 
$arr = array(1, 2, 'b'=>'green', 2);
$arr = array_unique($arr);

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

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');
$arr = array_replace($arr, $arr1, $arr2); 

print_r($arr); // [ d, e, c ]

Mapping

Same as array_walk (which needs reference)
 
function cube($n)
{
    return pow($n, 3);
}

$a = array(1,2,3);
$b = array_map('cube', $a);

print_r($b); // [0] => 1 [1] => 8 [2] => 27
Compact example
 
$b = array_map(
    create_function(
        '$x', 'return pow($x, 3);'
    ), array(1,2,3));

print_r($b); // [ 1, 8, 27 ]

Walk

Apply a user function to every member of an array.
 
$arr = array (1,2,3);
array_walk($arr, create_function('&$x', '$x *= 2;'));

print_r($arr); // [ 2, 4, 6 ]

Padding

Pad array to the specified length with a value.
 
$array = array(1,2,3);
$arr = array_pad($array, 6, 0); 

print_r($arr); // [ 1, 2, 3, 0, 0, 0 ]
echo str_pad(111, 6, 0); // 111000

Slice

Extract a slice of the array
 
$arr = [1, 2, 3, 4, 5];

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

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

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)); 
print_r($arr); // [ 1, 2, 10, 11 ]

Flip

array_flip() - values became keys
 
$a = array('a', 'b');
$b = array_flip($a);

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

Reverse

Inverts the order of the array's elements.
 
$a = array('a', 'b');
$b = array_reverse($a); 

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

Questions    
Array sort
        A B C D E F
🔔
1/3