SlideShare a Scribd company logo
1 of 33
Download to read offline
PHP, Arrays & Functional
Programming
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/
4/2016
By the way:
We’re always looking for
Full Stack Developers
4/2016
Sclable Platform Senior Developer
PL/PGSQL - PHP - JS
← full stack →
Aviation Enthusiast
Michael Rutz
4/2016
f(x) === f(x)
Immutable
y = x; f(x); x === y;
No side effects
Functional Programming
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
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
4/2016
FPHP?
Functional Programming in PHP
4/2016
Imperative design, but
Closures ✓
Functional Programming in PHP
4/2016
$ids = array_map(function ($item) {
return $item->id;
}, $list);
// js / ES2015
let ids = list.map(item => item.id);
Functional Programming in PHP
4/2016
Implemented the right way,
code readability can be improved.
Functional Programming in PHP
4/2016
https://secure.php.net/manual/en/book.array.php
Array Functions
4/2016
Performance !
Nice shorthands !
Array Functions
4/2016
$idsToLoad = array_diff($idsRequired, $idsLoaded);
// e.g. cities -> countries
$referencedCountryIds = array_unique([1,1,2,3]);
Array Functions
4/2016
array array_map(callable, array, array...)
bool array_walk(&array, callable)
array array_unique(array, sort_flags)
Inconsistent API
4/2016
https://github.com/sclable/array-functions
composer require sclable/array-functions
class ArrayWrap
4/2016
Normalized Params
OO & FP Approach
class ArrayWrap
4/2016
// e.g. cities -> countries
$referencedCountryIds = ArrayWrap::create($cities)
->map(function ($city) { return->countryId; })
->unique();
e.g.
4/2016
More e.g.
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);
}
4/2016
ArrayWrap::create([])
->pad(10, 0)
->map(function () { return rand(); })
->max();
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
4/2016
foreach vs. array_map/array_walk
Performance Considerations
4/2016
! major performance impact on closures !
xDebug
4/2016
$ids = []
foreach ($models as $model) {
$ids[] = $model->id;
}
$ids = array_map(
function ($model) { return $model->id; },
$models
);
Extract a list of ids
4/2016
Foreach vs. Array_map 1:0
Extract a list of ids
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
4/2016
Foreach vs. Array_map 2:0
Assign by id
4/2016
$yelled = [‘OH’, ‘SO’, ‘LOUD’];
$pssst = [];
foreach ($yelled as $v) {
$pssst[] = strtolower($v);
}
$pssst = array_map(‘strtolower’, $yelled);
Apply native functions
4/2016
Foreach vs. Array_map 2:1
Apply native functions
4/2016
Performance.
But readability!
Conclusions
4/2016
Performance.
But readability!
Conclusions
+ It looks cool!
4/2016
Thank you.
That’s all folks!

More Related Content

What's hot

(Meta 5) ejemplo vectores 2 dev c++
(Meta 5) ejemplo vectores 2 dev c++ (Meta 5) ejemplo vectores 2 dev c++
(Meta 5) ejemplo vectores 2 dev c++
Eli Diaz
 
(Meta 5) ejemplo vectores dev c++
(Meta 5) ejemplo vectores dev c++ (Meta 5) ejemplo vectores dev c++
(Meta 5) ejemplo vectores dev c++
Eli Diaz
 

What's hot (16)

Aggregate
AggregateAggregate
Aggregate
 
Osmose-QA OpenData
Osmose-QA OpenDataOsmose-QA OpenData
Osmose-QA OpenData
 
Bcsl 033 data and file structures lab s2-2
Bcsl 033 data and file structures lab s2-2Bcsl 033 data and file structures lab s2-2
Bcsl 033 data and file structures lab s2-2
 
Odd number
Odd numberOdd number
Odd number
 
Bcsl 033 data and file structures lab s1-1
Bcsl 033 data and file structures lab s1-1Bcsl 033 data and file structures lab s1-1
Bcsl 033 data and file structures lab s1-1
 
Ds
DsDs
Ds
 
Binary search
Binary searchBinary search
Binary search
 
Ps installedsoftware
Ps installedsoftwarePs installedsoftware
Ps installedsoftware
 
Palindrome number program c
Palindrome number program cPalindrome number program c
Palindrome number program c
 
(Meta 5) ejemplo vectores 2 dev c++
(Meta 5) ejemplo vectores 2 dev c++ (Meta 5) ejemplo vectores 2 dev c++
(Meta 5) ejemplo vectores 2 dev c++
 
(Meta 5) ejemplo vectores dev c++
(Meta 5) ejemplo vectores dev c++ (Meta 5) ejemplo vectores dev c++
(Meta 5) ejemplo vectores dev c++
 
Advanced Crystal Reports: Techniques for compiling Annual Reports & other sta...
Advanced Crystal Reports: Techniques for compiling Annual Reports & other sta...Advanced Crystal Reports: Techniques for compiling Annual Reports & other sta...
Advanced Crystal Reports: Techniques for compiling Annual Reports & other sta...
 
8.1
8.18.1
8.1
 
WAP to initialize different objects with different values in java
WAP to initialize different objects with different values in javaWAP to initialize different objects with different values in java
WAP to initialize different objects with different values in java
 
Positive (2)
Positive (2)Positive (2)
Positive (2)
 
Euler method in c
Euler method in cEuler method in c
Euler method in c
 

Viewers also liked

SuccessFactors_WFA_Admin_Certification
SuccessFactors_WFA_Admin_CertificationSuccessFactors_WFA_Admin_Certification
SuccessFactors_WFA_Admin_Certification
Charmi Jilka
 
Reference for Pawala Ariyathilaka (2)
Reference for Pawala Ariyathilaka (2)Reference for Pawala Ariyathilaka (2)
Reference for Pawala Ariyathilaka (2)
Pawala Ariyathilaka
 
P3O - The Value Adding PMO - from Strategy to Projects
P3O - The Value Adding PMO - from Strategy to ProjectsP3O - The Value Adding PMO - from Strategy to Projects
P3O - The Value Adding PMO - from Strategy to Projects
Tony Vynckier
 

Viewers also liked (18)

(DVO311) Containers, Red Hat & AWS For Extreme IT Agility
(DVO311) Containers, Red Hat & AWS For Extreme IT Agility(DVO311) Containers, Red Hat & AWS For Extreme IT Agility
(DVO311) Containers, Red Hat & AWS For Extreme IT Agility
 
SuccessFactors_WFA_Admin_Certification
SuccessFactors_WFA_Admin_CertificationSuccessFactors_WFA_Admin_Certification
SuccessFactors_WFA_Admin_Certification
 
Reference for Pawala Ariyathilaka (2)
Reference for Pawala Ariyathilaka (2)Reference for Pawala Ariyathilaka (2)
Reference for Pawala Ariyathilaka (2)
 
Casos Aprobados 1543 - 08 de octubre 2014
Casos Aprobados 1543 - 08 de octubre 2014Casos Aprobados 1543 - 08 de octubre 2014
Casos Aprobados 1543 - 08 de octubre 2014
 
Ejercicio final de microsoft word
Ejercicio final de microsoft wordEjercicio final de microsoft word
Ejercicio final de microsoft word
 
Fungsi neuroendokrin
Fungsi neuroendokrin Fungsi neuroendokrin
Fungsi neuroendokrin
 
Microservices With SenecaJS
Microservices With SenecaJSMicroservices With SenecaJS
Microservices With SenecaJS
 
Abstracción geometria y proporciones
Abstracción geometria y proporciones Abstracción geometria y proporciones
Abstracción geometria y proporciones
 
Certificados Locutor Acta 20
Certificados Locutor Acta 20Certificados Locutor Acta 20
Certificados Locutor Acta 20
 
Certificados Locutor Acta 6
Certificados Locutor Acta 6Certificados Locutor Acta 6
Certificados Locutor Acta 6
 
Certificados Locutor Acta 1
Certificados Locutor Acta 1Certificados Locutor Acta 1
Certificados Locutor Acta 1
 
Certificados Locutor Acta 10
Certificados Locutor Acta 10Certificados Locutor Acta 10
Certificados Locutor Acta 10
 
La recherche de l'efficience - Lectra
La recherche de l'efficience - LectraLa recherche de l'efficience - Lectra
La recherche de l'efficience - Lectra
 
P3O - The Value Adding PMO - from Strategy to Projects
P3O - The Value Adding PMO - from Strategy to ProjectsP3O - The Value Adding PMO - from Strategy to Projects
P3O - The Value Adding PMO - from Strategy to Projects
 
1 corinthians 13
1 corinthians 131 corinthians 13
1 corinthians 13
 
Database Consolidation using Oracle Multitenant
Database Consolidation using Oracle MultitenantDatabase Consolidation using Oracle Multitenant
Database Consolidation using Oracle Multitenant
 
使用 AWS Step Functions 開發 Serverless 服務
使用 AWS Step Functions 開發 Serverless 服務使用 AWS Step Functions 開發 Serverless 服務
使用 AWS Step Functions 開發 Serverless 服務
 
Introduction à Twitter
Introduction à TwitterIntroduction à Twitter
Introduction à Twitter
 

Similar to PHP, Arrays & Functional Programming

PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
elliando dias
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
elliando dias
 
Web app development_php_06
Web app development_php_06Web app development_php_06
Web app development_php_06
Hassen Poreya
 
Clean code for WordPress
Clean code for WordPressClean code for WordPress
Clean code for WordPress
mtoppa
 

Similar to PHP, Arrays & Functional Programming (20)

PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
Tidy Up Your Code
Tidy Up Your CodeTidy Up Your Code
Tidy Up Your Code
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
 
Be pragmatic, be SOLID (at Boiling Frogs, Wrocław)
Be pragmatic, be SOLID (at Boiling Frogs, Wrocław)Be pragmatic, be SOLID (at Boiling Frogs, Wrocław)
Be pragmatic, be SOLID (at Boiling Frogs, Wrocław)
 
07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards
 
OOP Is More Than Cars and Dogs
OOP Is More Than Cars and DogsOOP Is More Than Cars and Dogs
OOP Is More Than Cars and Dogs
 
OOP is more than Cars and Dogs
OOP is more than Cars and Dogs OOP is more than Cars and Dogs
OOP is more than Cars and Dogs
 
Web app development_php_06
Web app development_php_06Web app development_php_06
Web app development_php_06
 
The Truth About Lambdas in PHP
The Truth About Lambdas in PHPThe Truth About Lambdas in PHP
The Truth About Lambdas in PHP
 
PHP7 Presentation
PHP7 PresentationPHP7 Presentation
PHP7 Presentation
 
Why async and functional programming in PHP7 suck and how to get overr it?
Why async and functional programming in PHP7 suck and how to get overr it?Why async and functional programming in PHP7 suck and how to get overr it?
Why async and functional programming in PHP7 suck and how to get overr it?
 
GlueCon 2016 - Threading in JavaScript
GlueCon 2016 - Threading in JavaScriptGlueCon 2016 - Threading in JavaScript
GlueCon 2016 - Threading in JavaScript
 
Clean code for WordPress
Clean code for WordPressClean code for WordPress
Clean code for WordPress
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
 
Giới thiệu PHP 7
Giới thiệu PHP 7Giới thiệu PHP 7
Giới thiệu PHP 7
 
The FPDF Library
The FPDF LibraryThe FPDF Library
The FPDF Library
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenarios
 
Phpspec tips&amp;tricks
Phpspec tips&amp;tricksPhpspec tips&amp;tricks
Phpspec tips&amp;tricks
 
Drupaljam xl 2019 presentation multilingualism makes better programmers
Drupaljam xl 2019 presentation   multilingualism makes better programmersDrupaljam xl 2019 presentation   multilingualism makes better programmers
Drupaljam xl 2019 presentation multilingualism makes better programmers
 

Recently uploaded

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Recently uploaded (20)

Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 

PHP, Arrays & Functional Programming