More Related Content Similar to PHP, Arrays & Functional Programming (20) PHP, Arrays & Functional Programming2. 4/2016
Model Driven Software Development
Sclable transforms your knowledge into
enterprise-grade, ready-to-go Business Applications.
Sclable Business Solutions GmbH
https://sclable.com/
6. 4/2016
$first = 0;
$second = 1;
for ($i = 0; $i < 10; $i++) {
echo $first . PHP_EOL;
$tmp = $first;
$first = $second;
$second += $tmp;
}
Functional Programming
Global state has changed
7. 4/2016
function fibonacci($n, $first = 0, $second = 1) {
if ($n === 0) return '';
return $first . PHP_EOL
. fibonacci(--$n, $second, $first + $second);
}
echo fibonacci(10);
Functional Programming
Global state untouched
Immutable
18. 4/2016
// e.g. cities -> countries
$referencedCountryIds = ArrayWrap::create($cities)
->map(function ($city) { return->countryId; })
->unique();
e.g.
20. 4/2016
$array = array_pad([], 10, 0);
foreach ($array as &$item) {
$item = rand();
}
// find max
$max = null;
foreach ($array as $item) {
$max = $max === null ?
$item : max($max, $item);
}
22. 4/2016
// [x] immutable
// [x] no side effects
$emptyArr = ArrayWrap::create([]);
$padded = $emptyArr->pad(10, 0);
$randList = $padded->map( … );
$max = $randList->max();
var_dump($emptyArr === $padded); // false
var_dump($padded === $randList); // false
25. 4/2016
$ids = []
foreach ($models as $model) {
$ids[] = $model->id;
}
$ids = array_map(
function ($model) { return $model->id; },
$models
);
Extract a list of ids
27. 4/2016
$assigned = [];
foreach ($instances as $instance) {
$assigned[$instance->id] = $instance;
}
$assigned = array_combine(array_map(
function ($instance) {return $instance->id;},
$instances
), $instances);
Assign by id
29. 4/2016
$yelled = [‘OH’, ‘SO’, ‘LOUD’];
$pssst = [];
foreach ($yelled as $v) {
$pssst[] = strtolower($v);
}
$pssst = array_map(‘strtolower’, $yelled);
Apply native functions