Introduction to Functional Programming for a PHP developer

You are currently viewing Introduction to Functional Programming for a PHP developer
  • Reading time:6 mins read
  • Post comments:1 Comment
  • Post last modified:November 7, 2021

Introduction

PHP is a general-purpose language with over 30+ years of history. It picked up a lot of features and paradigms over the years to make it as easy and as powerful it can be to everyone from novice programmers to enterprise developers.

Though the imperative style of programming is still here in PHP most new developers are learning and coding using Object Oriented features, especially considering MVC has become a defacto standard when it comes to web development. A lot of frameworks advertise their MVC architecture as a primary feature and list out several benefits it provides everyone from the separation of logic and view to scalability over time. This MVC architecture-heavy approach made Object-Oriented programming a must considering Classes where must achieve it.

Nowadays a new paradigm has picked up some steam, Functional Programming. It’s not new, languages branded as functional are old and the concepts behind them are even older. The idea of its widespread adoption has picked up new steam nowadays considering a new developer’s first introduction to Functional programming doesn’t even have to come from Pure Functional languages, their own favorite language which they have been developing for several years started adding several features from functional languages.

Functional concepts Map, Filter, Reduce feels like are in every programming language out there replacing code with if’s and for’s with elegant looking operations with help of these functions.

What is even Functional Programming?

Well searching for it first answer you get for it might be from Wikipedia

In computer science, functional programming is a programming paradigm where programs are constructed by applying and composing functions.

Wikipedia

Well, that simple definition doesn’t help to understand anything about it especially in the context of PHP. Next few lines you come across an explanation which I think is much better in describing what functional programming is. Instead of using an imperative style of programming functional programming uses a declarative approach. What it means instead of specifying how to do something exactly you just declare what you want to do.

An Example in Imperative Style

For Ex. You have a string “1 2 3 4 5” and you want to add all the numbers in the imperative style you would

  • Define $sum = 0
  • Iterate over the string
  • Skip if current character is a space
  • Add it to $sum (thanks to dynamic typing no cast)
  • Return $sum

Here’s sample code in PHP

<?php 

$input = "1 2 3 4 5";

function addString ($string) {
  $sum = 0;

  for ($i = 0; $i < strlen($string); ++$i) {
    if ($string[$i] === " ") continue;
    $sum += $string[$i];
  }
  
  return $sum;
}

echo "Output: " . addString($input);
Output: 15

If you have any experience with PHP or even Java, C#, python, or any C-like language this will seem familiar and you can easily read this and understand what’s happening. Imperative programming is very verbose in the sense that you need to define what you have to do. You just wanted to add numbers from string but you need to specify everything from skipping spaces to iterating over string like a list.

Same example with functional approach

<?php

$test = "1 2 3 4 5";

$sum = fn ($carry, $item) => $carry + $item;

$add = fn ($string) => array_reduce(
    explode(" ", $string),
    $sum
);

echo "Output: " . $add($test);
 
Output: 15

Explanation: Now you might have used the explode() function before it’s called string split in other languages, but of course explode() makes more sense.

Anyway, the output of explode() function is ['1', '2', '3', '4', '5'] an array of string numbers. That array then is passed to the array_reduce() function.

The first argument of array_reduce is an input array. The second argument is the callback in which the $sum variable containing an arrow function is passed. You might not be familiar with this syntax if you don’t catch up with new features. fn ($args) => expr is an arrow expression that is syntactic sugar for PHP’s previous anonyms functions function ($args) use ($captureList) { body }. The older syntax is still in PHP and it’s not replaced by new syntax it achieves the same funcationality, just dropping $captureList and automatically returning the last line which can only have a single line as a body. Now array_reduce iterates over the entire array invoking function passing the initial value and first item of the array and then the result of that previous function call and the second element of the array and then result of that call and third element and so on till all the elements in the array are finished. Again because of PHP weak typing there’s no need to cast string to numbers and the initial value of null is considered as 0 for the first call.

Only defining what needs to be done and not how to dot it. For a trivial task to just add the numbers, there is already a function in PHP so it’s even shorter.

<?php

$test = "1 2 3 4 5";

echo "Output: " . array_sum(explode(" ", $test));
 
Output: 15

This makes the example even smaller. You get the idea of functional programming defining smaller functions that do one thing and then applying them.

Concepts in functional programming

  1. Pure functions: Functions as in mathematical sense that mapping certain input to certain output)
  2. No side effects: No change of global state, No changing provided input, no reading/writing of IO/DB, etc). If you want to change something just read the input and provide changes on copy.
  3. Declrative: Don’t define how to do it, define what you want to do.
  4. Functions as first class citizens: Functions can be assigned to variable, passed as an argument, can be returned by other functions and more.
  5. Recursion: Use of recursion instead of loops

There’s more to functional programming than what has been stated above, but just as an introduction this is sufficient. This is just a gentle introduction as functional programming as a whole is a vast discipline in computer science itself. I might go over real-world examples of Functional Programming in PHP. For now, you get the idea next time you code it might be good to choose a functional approach.

If you want to read more about arrow functions you can check out PHP’s documentation here. If you are interested in applying array functions to your data check out PHP’s array functions here, and if you are interested in functional programming you can check out this youtube video.

This Post Has One Comment

Leave a Reply