Functional Programming in PHP by Simon Holywell

Functional Programming in PHP by Simon Holywell

Author:Simon Holywell [Simon Holywell]
Language: eng
Format: epub
Tags: Core Programming
Publisher: php[architect]
Published: 2016-11-02T04:00:00+00:00


At the other end of the equation we have tail that will return a list with all but the first value in the array contained in it.

function tail(array $arr) { return array_slice($arr, 1); } tail([1,2,3,4,5]); // [2,3,4,5]

These two functions can be used together to work through a list using recursion.

function print_items(array $arr) { echo head($arr) . '-'; if(tail($arr)) print_items(tail($arr)); } print_items([1,2,3,4,5]); // 1-2-3-4-5-

6.2 Flattening lists

Lists of lists can be very helpful when dealing with complex datasets or when transforming an array via array_map() where it would return an array from the applied function. In some instances though, you have a list of lists that really should just be one list with all values at the top level. The problem could look something like:

$arr = [1, 2, 3, 4, 5]; $divisor = 10.5; $arr2 = array_map(function($x) use ($divisor) { return [$x, $x / $divisor, $x % $divisor]; }, $arr); // [ // [1, 0.095238095238095233, 1], // [2, 0.19047619047619047, 2], // [3, 0.2857142857142857, 3], // [4, 0.38095238095238093, 4], // [5, 0.47619047619047616, 5] // ]



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.