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