SlideShare a Scribd company logo
1 of 60
Download to read offline
COLLECTIONS
Laravel
MARABESI
ARRAYS?
An array is a data structure that contains a
group of elements.
"
https://techterms.com/definition/array
<?php
$array = array(
'foo' => 'bar',
'bar' => 'foo',
);
// as of PHP 5.4
$array = [
'foo' => 'bar',
'bar' => 'foo',
];
?>
http://php.net/manual/en/language.types.array.php
The IlluminateSupportCollection class
provides a fluent, convenient wrapper for
working with arrays of data.
"
https://laravel.com/docs/5.0/collections
In computer science, a collection or
container is a grouping of some variable
number of data items (possibly zero) that
have some shared significance to the
problem being solved and need to be
operated upon together in some controlled
fashion.
"
https://en.wikipedia.org/wiki/Collection_(abstract_data_type)
$collection = collect([ 1, 2, 3 ]);
$collection = collect([ 'foo', 'bar' ]);
https://laravel.com/docs/collections
$collection = collect([ new User() ]);
$collection = collect([ 1, 2, 3 ]);
$collection = collect([ 'foo', 'bar' ]);
$collection = collect([ new User() ]);
https://laravel.com/docs/collections
$collection = collect([ 1, 2, 3 ]);
$collection = collect([ 'foo', 'bar' ]);
$collection = collect([ new User() ]);
https://laravel.com/docs/collections
$collection = collect([ 1, 2, 3 ]);
$collection = collect([ 'foo', 'bar' ]);
$collection = collect([ new User() ]);
https://laravel.com/docs/collections
$collection = collect([ 1, 2, 3 ]);
$collection = collect([ 'foo', 'bar' ]);
$collection = collect([ new User() ]);
https://laravel.com/docs/collections
use IlluminateSupportCollection;
$collection = new Collection();
COLLECTIONS
ARRAYS
X
IT SEEMS TO
BE THE
SAME THING...
$collection = collect([
'bar', 'foo'
]);
$array = [
'foo' => 'bar',
'bar' => 'foo',
];
HOW WOULD
YOU DO A SUM
FUNCTION?
<?php
$numbers = [
1,
2,
3
];
$total = 0;
for ($i = 0; $i < count($numbers); $i++) {
$total += $numbers[$i];
}
SUM
<?php
$numbers = [
1,
2,
3
];
$collection = collect($numbers);
$collection->sum();
SUM
HOW WOULD
YOU DO AN
AVG
FUNCTION?
<?php
$numbers = [
1,
2,
3
];
$total = 0;
for ($i = 0; $i < count($numbers); $i++) {
$total += $numbers[$i];
}
$total = $total / count($numbers);
AVG
<?php
$numbers = [
1,
2,
3
];
$collection = collect($numbers);
$collection->avg();
AVG
HOW WOULD
YOU DO A
SORT
FUNCTION?
<?php
$data = [
'c',
'd',
'a',
'b'
];
sort($data);
SORT
<?php
$data = [
'c',
'd',
'a',
'b'
];
$collection = collect($data);
$result = $collection->sort();
$values = $result->values()->all();
SORT
AVOID
NOTICES
<?php
$numbers = [
1,
2,
3
];
$numbers[4];
NOTICE
<?php
$numbers = [
1,
2,
3
];
$collection = collect($numbers);
$collection->get(4);
NOTICE
NULL
<?php
$numbers = [
1,
2,
3
];
$collection = collect($numbers);
$collection->get(4, 0);
NOTICE
0 (Zero)
<?php
$numbers = [
1,
2,
3
];
for ($i = 0; $i < count($numbers); $i++) {
$numbers[$i] = $numbers[$i] * 2;
}
MAP
<?php
$numbers = [
1,
2,
3
];
$collection = collect($numbers);
$result = $collection->map(function($item, $key) {
return $item * 2;
});
MAP
<?php
$numbers = [
1,
2,
3
];
for ($i = 0; $i < count($numbers); $i++) {
if ($numbers[$i] === 2) {
unset($numbers[$i]);
}
}
FILTER
<?php
$numbers = [
1,
2,
3
];
$collection = collect($numbers);
$result = $collection->filter(function($item, $key) {
return $item !== 2;
});
FILTER
!!! BONUS !!!
<?php
use IlluminateSupportStr;
Collection::macro('toUpper', function () {
return $this->map(function ($value) {
return Str::upper($value);
});
});
$collection = collect(['first', 'second']);
$upper = $collection->toUpper();
PERF TIME
<?php
$startTime = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
$data = [
'c',
'd',
'a',
'b',
];
sort($data);
}
echo 'Time: ' . number_format(( microtime(true) - $startTime), 4) . ' Seconds';
https://stackoverflow.com/questions/1200214/how-can-i-measure-the-speed-of-code-written-in-php
STEP PHP TIME
First run 7.1.7 2.4553
Second run 7.1.7 2.6595
Third run 7.1.7 2.4450
STEP PHP TIME
First run 7.2.0beta1 2.0294
Second run 7.2.0beta1 2.0281
Third run 7.2.0beta1 2.7551
<?php
require 'vendor/autoload.php';
use IlluminateSupportCollection;
$startTime = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
$data = [
'c',
'd',
'a',
'b'
];
$collection = collect($data);
$result = $collection->sort();
$result->values()->all();
}
echo 'Time: ' . number_format(( microtime(true) - $startTime), 4) . ' Seconds';
https://stackoverflow.com/questions/1200214/how-can-i-measure-the-speed-of-code-written-in-php
STEP PHP TIME
First run 7.1.7 11.7716
Second run 7.1.7 12.4548
Third run 7.1.7 12.2648
STEP PHP TIME
First run 7.2.0beta1 11.0426
Second run 7.2.0beta1 10.7730
Third run 7.2.0beta1 9.2139
WHY SHOULD I
USE
COLLECTIONS?
1. Eloquent models,
return collections by
default
2. Keep your code
readable
Avoid nested loops or unnecessary logic
3. Good
Documentation
LEARNING
MORE
https://adamwathan.me/refactoring-to-collections
https://leanpub.com/laravelcollectionsunraveled
https://github.com/illuminate/support/blob/master/Collection.php
MARABESI

More Related Content

What's hot

Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arrays
mussawir20
 
Advanced modulinos
Advanced modulinosAdvanced modulinos
Advanced modulinos
brian d foy
 

What's hot (19)

Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arrays
 
Smarty Template
Smarty TemplateSmarty Template
Smarty Template
 
Smarty Template
Smarty TemplateSmarty Template
Smarty Template
 
4.1 PHP Arrays
4.1 PHP Arrays4.1 PHP Arrays
4.1 PHP Arrays
 
The Magic Of Tie
The Magic Of TieThe Magic Of Tie
The Magic Of Tie
 
Chap 3php array part1
Chap 3php array part1Chap 3php array part1
Chap 3php array part1
 
Revisiting SOLID Principles
Revisiting  SOLID Principles Revisiting  SOLID Principles
Revisiting SOLID Principles
 
Storytelling By Numbers
Storytelling By NumbersStorytelling By Numbers
Storytelling By Numbers
 
Advanced modulinos
Advanced modulinosAdvanced modulinos
Advanced modulinos
 
Phpspec tips&amp;tricks
Phpspec tips&amp;tricksPhpspec tips&amp;tricks
Phpspec tips&amp;tricks
 
Writing Sensible Code
Writing Sensible CodeWriting Sensible Code
Writing Sensible Code
 
Advanced modulinos trial
Advanced modulinos trialAdvanced modulinos trial
Advanced modulinos trial
 
Climbing the Abstract Syntax Tree (php[world] 2019)
Climbing the Abstract Syntax Tree (php[world] 2019)Climbing the Abstract Syntax Tree (php[world] 2019)
Climbing the Abstract Syntax Tree (php[world] 2019)
 
How to write code you won't hate tomorrow
How to write code you won't hate tomorrowHow to write code you won't hate tomorrow
How to write code you won't hate tomorrow
 
Intoduction to php arrays
Intoduction to php arraysIntoduction to php arrays
Intoduction to php arrays
 
Perl Bag of Tricks - Baltimore Perl mongers
Perl Bag of Tricks  -  Baltimore Perl mongersPerl Bag of Tricks  -  Baltimore Perl mongers
Perl Bag of Tricks - Baltimore Perl mongers
 
What's New in Perl? v5.10 - v5.16
What's New in Perl?  v5.10 - v5.16What's New in Perl?  v5.10 - v5.16
What's New in Perl? v5.10 - v5.16
 
dcs plus Catalogue 2015
dcs plus Catalogue 2015dcs plus Catalogue 2015
dcs plus Catalogue 2015
 
Simple uses of ADRCI
Simple uses of ADRCISimple uses of ADRCI
Simple uses of ADRCI
 

Similar to Laravel collections an overview - Laravel SP

Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128
PrinceGuru MS
 
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
camp_drupal_ua
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
jsmith92
 
第49回Php勉強会@関東 Datasource
第49回Php勉強会@関東 Datasource第49回Php勉強会@関東 Datasource
第49回Php勉強会@関東 Datasource
Kaz Watanabe
 

Similar to Laravel collections an overview - Laravel SP (20)

Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128
 
PHP tips and tricks
PHP tips and tricks PHP tips and tricks
PHP tips and tricks
 
PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007
 
Chapter 2 wbp.pptx
Chapter 2 wbp.pptxChapter 2 wbp.pptx
Chapter 2 wbp.pptx
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
Intermediate PHP
Intermediate PHPIntermediate PHP
Intermediate PHP
 
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
 
Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4
 
Intro to The PHP SPL
Intro to The PHP SPLIntro to The PHP SPL
Intro to The PHP SPL
 
Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09
 
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
 
UNIT IV (4).pptx
UNIT IV (4).pptxUNIT IV (4).pptx
UNIT IV (4).pptx
 
PHP Array Functions.pptx
PHP Array Functions.pptxPHP Array Functions.pptx
PHP Array Functions.pptx
 
Array Methods.pptx
Array Methods.pptxArray Methods.pptx
Array Methods.pptx
 
New SPL Features in PHP 5.3
New SPL Features in PHP 5.3New SPL Features in PHP 5.3
New SPL Features in PHP 5.3
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
Marcs (bio)perl course
Marcs (bio)perl courseMarcs (bio)perl course
Marcs (bio)perl course
 
PHP and MySQL
PHP and MySQLPHP and MySQL
PHP and MySQL
 
第49回Php勉強会@関東 Datasource
第49回Php勉強会@関東 Datasource第49回Php勉強会@関東 Datasource
第49回Php勉強会@関東 Datasource
 
Arrays in php
Arrays in phpArrays in php
Arrays in php
 

More from Matheus Marabesi

More from Matheus Marabesi (20)

IoT Project postmortem
IoT Project postmortemIoT Project postmortem
IoT Project postmortem
 
Testing with Laravel - 7Masters 2018 (Laravel)
Testing with Laravel - 7Masters 2018 (Laravel)Testing with Laravel - 7Masters 2018 (Laravel)
Testing with Laravel - 7Masters 2018 (Laravel)
 
Becoming an author - Sharing knowledge
Becoming an author - Sharing knowledgeBecoming an author - Sharing knowledge
Becoming an author - Sharing knowledge
 
Docker 101 - Getting started
Docker 101 - Getting startedDocker 101 - Getting started
Docker 101 - Getting started
 
Introduction to IoT and PHP - Nerdzão day #1
Introduction to IoT and PHP - Nerdzão day #1Introduction to IoT and PHP - Nerdzão day #1
Introduction to IoT and PHP - Nerdzão day #1
 
Todos os passos para a certificação PHP - PHPExperience2017
Todos os passos para a certificação PHP - PHPExperience2017 Todos os passos para a certificação PHP - PHPExperience2017
Todos os passos para a certificação PHP - PHPExperience2017
 
IoT powered by PHP and streams - PHPExperience2017
IoT powered by PHP and streams - PHPExperience2017IoT powered by PHP and streams - PHPExperience2017
IoT powered by PHP and streams - PHPExperience2017
 
Control your house with the elePHPant - PHPConf2016
Control your house with the elePHPant - PHPConf2016Control your house with the elePHPant - PHPConf2016
Control your house with the elePHPant - PHPConf2016
 
Laravel, the right way - PHPConference 2016
Laravel, the right way - PHPConference 2016Laravel, the right way - PHPConference 2016
Laravel, the right way - PHPConference 2016
 
GDG Passo fundo - Apps with unit tests (Karma + jasmine + angular)
GDG Passo fundo - Apps with unit tests (Karma + jasmine + angular)GDG Passo fundo - Apps with unit tests (Karma + jasmine + angular)
GDG Passo fundo - Apps with unit tests (Karma + jasmine + angular)
 
Laravel the right way
Laravel   the right wayLaravel   the right way
Laravel the right way
 
7masters - MongoDb
7masters - MongoDb7masters - MongoDb
7masters - MongoDb
 
TDC São Paulo 2016 - Become a jedi with php streams
TDC São Paulo 2016 - Become a jedi with php streamsTDC São Paulo 2016 - Become a jedi with php streams
TDC São Paulo 2016 - Become a jedi with php streams
 
TDC 2016 (Florianópolis) - Vá para o próximo nível - Dicas e truques para a c...
TDC 2016 (Florianópolis) - Vá para o próximo nível - Dicas e truques para a c...TDC 2016 (Florianópolis) - Vá para o próximo nível - Dicas e truques para a c...
TDC 2016 (Florianópolis) - Vá para o próximo nível - Dicas e truques para a c...
 
Darkmira Tour PHP 2016 - Automatizando Tarefas com Phing
Darkmira Tour PHP 2016 - Automatizando Tarefas com PhingDarkmira Tour PHP 2016 - Automatizando Tarefas com Phing
Darkmira Tour PHP 2016 - Automatizando Tarefas com Phing
 
scdevsumit 2016 - Become a jedi with php streams
scdevsumit 2016 - Become a jedi with php streamsscdevsumit 2016 - Become a jedi with php streams
scdevsumit 2016 - Become a jedi with php streams
 
ZCPE - PHP Conference 2015
ZCPE   - PHP Conference 2015ZCPE   - PHP Conference 2015
ZCPE - PHP Conference 2015
 
Phing - PHP Conference 2015
Phing -  PHP Conference 2015Phing -  PHP Conference 2015
Phing - PHP Conference 2015
 
CK 10 - Automate all the things 2.0
CK 10 - Automate all the things 2.0CK 10 - Automate all the things 2.0
CK 10 - Automate all the things 2.0
 
TDC2015 Porto Alegre - Automate everything with Phing !
TDC2015 Porto Alegre - Automate everything with Phing !TDC2015 Porto Alegre - Automate everything with Phing !
TDC2015 Porto Alegre - Automate everything with Phing !
 

Recently uploaded

introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 

Recently uploaded (20)

How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 

Laravel collections an overview - Laravel SP