Memory App
Programming
 




Range

range() - Creates an array containing a range of elements

$images = range(1,100); // 1,2,3 ...
$images = range(0,100,10); // 10,20,30 ...
(1/6)

Chunks

array_chunk() - split array into chunks

$images = range(0,100);

$chunks = array_chunk($images, 2);
    // 2 - size of each chunk
    // 1 - default

foreach($chunks as $chunk) { // 50 chunks

    foreach($chunk as $v) {
        echo $v;
    }
}
(2/6)

Combine

array_combine() - key from arr1, values from arr2

$keys = array('green', 'yellow');
$values = array('avocado', 'banana');

$arr = array_combine($keys, $values);

// [green] => avocado [yellow] => banana 
(3/6)

Merge

array_merge() - Merge one or more arrays

$one = 'foo';
$two = array('a', 'b');

$result = array_merge($one, $two);
    // Warning: Argument #1 is not an array

$result = array_merge((array)$one, $two);
    // Array ( [0] => foo [1] => a [2] => b ) 
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one.

$arr1 = array('color'=> 'red', 1);
$arr2 = array('a', 'color'=>'green');

$arr3 = array_merge($arr1, $arr2);

// [color] => green [0] => 1 [1] => a
If, however, the arrays contain numeric keys, the later value will not overwrite the original value.

$arr1 = array(1,2);
arr2 = array(3,4);

$arr3 = array_merge($arr1, $arr2);

// [0] => 1 [1] => 2 [2] => 3 [3] => 4
If don't want to ovewrite the elements from the first array use the + array union operator.

$arr1 = array('color'=> 'red', 1);
$arr2 = array('color'=>'green', 2, 3);

$arr3 = $arr1 + $arr2;

// [color] => red [0] => 1 [1] => 3
(4/6)

Differences

array_diff() - difference of arrays All the values of $a that do not appear in $b are retained.

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

print_r(array_diff ($a, $b)); // [1] => 2
(5/6)

Intersaction

array_intersect() - intersect arrays Like with array_diff() array_intersect only keeps in consideration the value of each element.

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

print_r(array_intersect ($a, $b)); // [0] => 1 [2] => 3


Questions



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