Memory App
Programming
 




Values exists

in_array() - Check if a value exists in an array

$array = array('a'=>1, 'b'=>2, 'c'=>3);

echo in_array(1, $array); // Output: 1
(1/7)

Key exists

array_key_exists() - Checks if the given key exists in the array

$arr = array ('a' => NULL, 'b' => 2); 

echo isset ($arr['a']); // False 

echo array_key_exists('a', $arr); // True
(2/7)

Sum

array_sum() - sum of values in an array

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

echo array_sum($arr); // 6
(3/7)

Factorial

array_product() - factorial

$n = 3;

echo array_product(range(1, $n)); 

// Ouput: 6 = 3! = 1*2*3
(4/7)

Search value

array_search() - searches value, returns key May return boolean false (always use indentical operator)

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

echo array_search(4, $array); // Output 3
Wrong

if (array_search(5, $array) == 0) { // !! true

    echo 'Found'; // Output: Found!
}
Corect

if (array_search(5, $array) === 0) { // false

    echo 'Found'; // Output nothing
}
(5/7)

Keys

array_keys() - Return all the keys If the optional search_value is specified, only the keys for that value are returned

$arr = array('a', 'b', 'a', 'c', 'a', '0', false);

print_r(array_keys($arr)); // [ 0, 1, 2, 3, 4, 5, 6 ]
Search_value provided

print_r(array_keys($arr, 'a')); // [ 0, 2, 4 ]
Strict search (identical comparation)

print_r(array_keys($arr, '0')); // [ 5, 6 ] !! not true

print_r(array_keys($arr, '0', true)); // [ 5 ] corect
(6/7)

Count

count() - Count all elements in an array

echo count(array(1,2,3)); // Output: 3

// For a variable that isn't set

echo count($arr); // Output: 0

// Caution for false

echo count(false); // Output: 1


Questions



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