PROGRAMMING

 
REMEMBERS




Last update:   29-10-2021

Array Operations

Exists

To check if array exists use is_array, not count.
 
$a = array();

echo count($a); // 0
echo is_array($a); // true

Reverse

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

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

Next

Reset, key, next, current are used when working with array internal pointer.
 
$arr = array('a' => 1, 'b' => 2, 'c' => 3);
reset($arr);

while (key($arr) !== NULL) {
    echo key($arr) . current($arr) . " "; // a1 b2 c3
    next($arr);
}
... 1 lines
 

Array map

Array_map is the 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); // [1, 8, 27] 
... 2 lines
 
 
$result = array_map
(
    create_function('$x', 'return pow($x, 3);'), array(1,2,3)
);

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

Array walk

Apply a user function to every member of an array.
 
$arr = array(1,2,3,4);

function setDouble($value) 
{ 
    echo $value * 2; // 2 4 6 8
}

array_walk($arr, 'setDouble');
... 1 lines
 
 
$arr = array(1,2,3,4);

function setDouble(&$value) // reference
{ 
    $value *= 2;
}

array_walk($arr, 'setDouble'); 

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

Keys destruction

Sorting destroys all the keys and rearange elements.
 
$arr = array('a'=>'foo', 'b'=>'bar', 'c'=>'baz');
sort($arr);

print_r($arr); //  [0] => bar [1] => baz [2] => foo 

Add element

 
$arr = array();
array_push($arr, 'bar', 'baz'); // add at the end

print_r($arr); // [bar, baz]
When only one value is being pushed [] is faster (no function call).
 
$arr = array('bar', 'baz');
$arr[] = 'foo';

var_dump($arr); //[bar, baz, foo]

Extract last

 
$arr = array('bar', 'baz');
$last = array_pop($arr);

echo $last; // baz
var_dump($arr); // array(1) { [0]=> string(3) "bar" }

Extract first

 
$arr = array('bar', 'baz');
$first = array_shift($arr);

print_r($arr); // [0] => baz

Add first

 
$arr = array('bar', 'baz');
array_unshift($arr, 'foo');

print_r($arr); // [foo, bar, baz]

Questions    
Array create

        A B C D E F
🔔
1/3