forked from bradtraversy/php-crash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
07_array_functions.php
66 lines (51 loc) · 1.48 KB
/
07_array_functions.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php
/* --------- Array Functions -------- */
/*
Functions to work with arrays
https://www.php.net/manual/en/ref.array.php
*/
$fruits = ['apple', 'banana', 'orange'];
// Get array length
echo count($fruits);
// Search array
echo in_array('banana', $fruits);
// Add to an array
$fruits[] = 'grape';
array_push($fruits, 'mango', 'raspberry');
array_unshift($fruits, 'kiwi'); // Adds to the beginning
// Remove from array
array_pop($fruits); // Removes last
array_shift($fruits); // Removes first
// Remove specific element
unset($fruits[2]);
// Split into chunks of 2
$chunkedArray = array_chunk($fruits, 2);
var_dump($chunkedArray);
// Concatenate arrays
$arr1 = [1, 2, 3];
$arr2 = [4, 5, 6];
$arr3 = array_merge($arr1, $arr2);
var_dump($arr3);
$arr4 = [...$arr1, ...$arr2]; // Use Spread
var_dump($arr4);
// Combine arrays (Keys & values)
$a = ['green', 'red', 'yellow'];
$b = ['avocado', 'apple', 'banana'];
$c = array_combine($a, $b);
// Array of keys
$keys = array_keys($c);
// Flip keys with values
$flipped = array_flip($c);
var_dump($flipped);
// Create array of numbers with range()
$numbers = range(1, 20);
// Map through array and create a new one
$newNumbers = array_map(function ($number) {
return "Number ${number}";
}, $numbers);
// Filter array
$lessThan10 = array_filter($numbers, fn($number) => $number < 10);
// Array Reduce
// "carry" holds the return value of the previous iteration
$sum = array_reduce($numbers, fn($carry, $number) => $carry + $number);
var_dump($sum);