SlideShare a Scribd company logo
SEMANTIC WEAPONS
PHP Conf 2016
HELLO STRANGER
SEMANTIC WEAPONS
$ id -un
– carlos@semantic.mx
– tweet me @cvences
– Founded a 4yo development shop
– semanticweapons.com
#phpconmx
and we’re hiring!
HELLO STRANGER
SEMANTIC WEAPONS
SEMANTIC WEAPONS
PHP for Python Developers
SEMANTIC WEAPONS
PHP for Python Developers
Web Development & General Scripting
SEMANTIC WEAPONS
$ membership operator _
$inArray = in_array(5, range(0, 10)) === TRUE;
SEMANTIC WEAPONS
$ membership operator _
in_array = 5 in range(10) == True
SEMANTIC WEAPONS
$ membership operator _
in_array = 5 in range(10) == True
>>> in_array
False
SEMANTIC WEAPONS
$ default values _
# counting dictionary keys
from collections import defaultdict
log = ['warn', 'error', 'debug', 'info', 'warn', 'debug', 'warn']
stats = defaultdict(int)
for entry in log:
stats[entry] += 1
SEMANTIC WEAPONS
$ default values _
// counting elements
$log = ['warn', 'error', 'debug', 'info', 'warn', 'debug', ‘warn'];
$stats = [];
foreach ($log as $entry){
$stats[$entry] = $stats[$entry]++ ?: 0;
}
SEMANTIC WEAPONS
$ default values _
// counting elements
$log = ['warn', 'error', 'debug', 'info', 'warn', 'debug', ‘warn'];
$stats = [];
foreach ($log as $entry){
$stats[$entry]++;
}
SEMANTIC WEAPONS
$ default values _
// counting elements
$log = ['warn', 'error', 'debug', 'info', 'warn', 'debug', ‘warn'];
$stats = [];
foreach ($log as $entry){
$stats[$entry]++;
}
# counting dictionary keys
from collections import defaultdict
log = ['warn', 'error', 'debug', 'info', 'warn', 'debug', ‘warn']
stats = defaultdict(int)
for entry in log:
stats[entry] += 1
SEMANTIC WEAPONS
Memory consumption
– C’s pointers
– SQL’s LIMIT statement
– strcmp, strcpy, strcat
– strncmp, strncpy, strncat
– buffer overflow
SEMANTIC WEAPONS
Memory consumption
– C’s pointers
– SQL’s LIMIT statement
– strcmp, strcpy, strcat
– strncmp, strncpy, strncat
– buffer overflow
¿Quién agregó
la clausula LIMIT
a mini SQL 1.x?
SEMANTIC WEAPONS
$ Array
function myRange($max = 10) {
$numeros = [];
$num = 1;
while ($num < $max) {
array_push($numeros, $num);
$num++;
}
return $numeros;
}
function sum($max = 10) {
$sumatoria = 0;
foreach (myRange($max) as $num) {
$sumatoria += $num;
}
echo $sumatoria;
}
sum(1000000);
SEMANTIC WEAPONS
$ Iterator
class NumberIter implements Iterator {
private $position = 0;
private $array = [];
public function __construct($array = []) {
$this->position = 0;
$this->array = $array;
}
public function rewind() {
$this->position = 0;
}
public function current() {
return $this->array[$this->position];
}
public function key() {
return $this->position;
}
public function next() {
++$this->position;
}
public function valid() {
return isset($this->array[$this->position]);
}
}
function sum($max = 10) {
$sumatoria = 0;
$numberIter = new NumberIter($array = range(1, ($max - 1)));
foreach ($numberIter as $num) {
$sumatoria += $num;
}
echo $sumatoria;
}
sum(1000000);
SEMANTIC WEAPONS
$ PHP Arrays vs Iterators
foreach (myRange($max) as $num) {
$sumatoria += $num;
}
foreach ($numberIter as $num) {
$sumatoria += $num;
}
SEMANTIC WEAPONS
Entering
Generators
SEMANTIC WEAPONS
$ Generators
function myRange($max = 10) {
// $numeros = [];
$num = 1;
while ($num < $max) {
yield $num;
$num++;
}
// return $numeros;
}
function sum($max = 10) {
$sumatoria = 0;
foreach (myRange($max) as $num) {
$sumatoria += $num;
}
echo $sumatoria;
}
sum(1000000);
SEMANTIC WEAPONS
Generators
– Implement Iterators
– DRY
– Can traverse with foreach
– foreach does not use IAP (>7.0.0)
– Uses hashtable iterators now
– Does not build an array in-memory
– Also speeds time to generate
Note: – Calling range(0, 1000000) will result in well over 100 MB of memory being used.
SEMANTIC WEAPONS
$ Iterators, Generators and Arrays
class NumberIter implements Iterator {
private $position = 0;
private $array = [];
public function __construct($array = []) {
$this->position = 0;
$this->array = $array;
}
public function rewind() {
$this->position = 0;
}
public function current() {
return $this->array[$this->position];
}
public function key() {
return $this->position;
}
public function next() {
++$this->position;
}
public function valid() {
return isset($this->array[$this->position]);
}
}
function myRange($max = 10) {
$num = 1;
while ($num < $max) {
yield $num;
$num++;
}
}
array range ($start, $end, $step)
SEMANTIC WEAPONS
$ Iterators, Generators and Arrays
class NumberIter implements Iterator {
private $position = 0;
private $array = [];
public function __construct($array = []) {
$this->position = 0;
$this->array = $array;
}
public function rewind() {
$this->position = 0;
}
public function current() {
return $this->array[$this->position];
}
public function key() {
return $this->position;
}
public function next() {
++$this->position;
}
public function valid() {
return isset($this->array[$this->position]);
}
}
function myRange($max = 10) {
$num = 1;
while ($num < $max) {
yield $num;
$num++;
}
}
SEMANTIC WEAPONS
Case of Study
SEMANTIC WEAPONS
$ PHP 7.1.0 RC2_
SEMANTIC WEAPONS
Using Generators
SEMANTIC WEAPONS
$ PHP 7.1.0 RC2_
SEMANTIC WEAPONS
Using Iterators
SEMANTIC WEAPONS
HELLO STRANGER
PHP 7.1.0 RC2
SEMANTIC WEAPONS
$ time
SEMANTIC WEAPONS
To be or not to be
– Using iterators is great
– foreach in 7.0.0 rocks!
– lists are fat, sequences evaluate lazily
– Lazy is good
SEMANTIC WEAPONS
Warning: sort() expects parameter 1 to be array, object given
SEMANTIC WEAPONS
But…
– Python iterators introduced in 2.2 (2001)
– range -> xrange -> range
– PHP yield introduced in 5.5.0+ (2013)
– Iterator name space may clash
– What’s wrong with iterator_to_array?
– PHP ArrayAccess
Blog Post: SPL Iterators against the performance
PHP Manual: /language.generators.overview.php
SEMANTIC WEAPONS
Readability
SEMANTIC WEAPONS
$ unpacking a list _
sum_of_numbers = sum([x**3 for x in range(10000)])
SEMANTIC WEAPONS
$ unpacking an array _
$sumOfNumbers = 0;
foreach (range(1, 10000) as $num) {
$sumOfNumbers += pow($num, 3);
}
SEMANTIC WEAPONS
$ unpacking an array _
// second try
$processArray = function($method, $array) {
return array_map($method, $array);
};
$sumOfNumbers = array_sum(
$processArray(
$method = function($x){return pow($x, 3);},
$array = range(0, 10000)
)
);
SEMANTIC WEAPONS
One liners
– means something in English
– easy to understand at first glance
SEMANTIC WEAPONS
$ unpacking an array _
$sumOfNumbers = 0;
foreach (range(1, 10000) as $value) {
$sumOfNumbers += pow($value, 3);
}
// second try
$processArray = function($method, $array) {
return array_map($method, $array);
};
$sumOfNumbers = array_sum(
$processArray(
$method = function($x){return pow($x, 3);},
$array = range(0, 10000)
)
);
// third try
$sumOfNumbers = array_sum(array_map(function($x){return pow($x, 3);}, range(0, 10000)));
SEMANTIC WEAPONS
$ readability _
sum_of_numbers = sum([x**3 for x in range(10000)])
$y = array_sum(array_map(function($x){return pow($x, 3);}, range(0, 10000)));
SEMANTIC WEAPONS
$ looping over two collections _
speakers = ['Javier', 'Joe', 'Rasmus', 'Carlos']
talks = ['Ansible', 'Loopless', 'Deploy', 'Python']
for speaker, talk in zip(speakers, talks):
print(speaker, talk)
SEMANTIC WEAPONS
$ looping over two collections _
$speakers = ['Javier', 'Joe', 'Rasmus', 'Carlos'];
$talks = ['Ansible', 'Loopless', 'Deploy', 'Python'];
$max = min(count($speakers), count($talks));
foreach(range(0, $max-1) as $i){
echo($speakers[$i] .' '. $talks[$i]);
}
SEMANTIC WEAPONS
$ looping over two collections _
// second approach
$speakers = ['Javier', 'Joe', 'Rasmus', 'Carlos'];
$talks = ['Ansible', 'Loopless', 'Deploy', 'Python'];
$meetupTalks = array_combine($speakers, $talks);
foreach($meetupTalks as $speaker => $talk){
echo "$speaker $talk";
}
SEMANTIC WEAPONS
$ looping over two collections _
for speaker, talk in zip(speakers, talks):
print(speaker, talk)
foreach(array_combine($speakers, $talks) as $speaker => $talk)
echo "$speaker $talk";
SEMANTIC WEAPONS
$ python iterators magic, tweet .@cvences
# dado un array asociativo, elimina todos los nombres que empiecen con la letra “c”

meetup_info = {

'Javier': 'Ansible',

'Joe': 'Loopsless',

'Rasmus': 'Deploy',

'Carlos': 'Python',

}



meetup_info = {key: meetup_info[key] for key in meetup_info if not key.lower().startswith('c')}
# dado un modelo con relationships, filtra los blogs cuyos autores tengan o no
# un nombre asignado. El título no incluye la palabra python y ordénalos por fecha
# de creación descendente.


Blog.objects
.filter(entry__authors__isnull=False, entry__authors__name__isnull=True)
.exclude(entry__title__icontains=‘python’)
.order_by(‘-created’)
SEMANTIC WEAPONS
$ python iterators magic
def fib(n):

return (4 << n * (3 + n)) // ((4 << 2 * n) - (2 << n) - 1) & ((2 << n) - 1)
def get_fibonacci_by_position(pos):

"""

Returns the fibonacci number at pos



"""

a, b = 1, 1



for _ in range(pos):

a, b = a + b, a



return b
PHP for Python Developers
carlos@semantic.mx
HELLO STRANGER
SEMANTIC WEAPONS

More Related Content

What's hot (20)

PPTX
Crafting beautiful software
Jorn Oomen
 
PDF
Codeware
Uri Nativ
 
PDF
Introdução ao Perl 6
garux
 
DOC
Jsphp 110312161301-phpapp02
Seri Moth
 
PDF
Doctrine fixtures
Bill Chang
 
PPTX
Electrify your code with PHP Generators
Mark Baker
 
PPT
PHP and MySQL
Sanketkumar Biswas
 
PDF
PHP for Adults: Clean Code and Object Calisthenics
Guilherme Blanco
 
PDF
The History of PHPersistence
Hugo Hamon
 
PDF
Database Design Patterns
Hugo Hamon
 
PDF
PHPUnit でよりよくテストを書くために
Yuya Takeyama
 
PDF
Design Patterns avec PHP 5.3, Symfony et Pimple
Hugo Hamon
 
PDF
The Perl6 Type System
abrummett
 
PDF
News of the Symfony2 World
Fabien Potencier
 
PDF
PHP 7 – What changed internally? (Forum PHP 2015)
Nikita Popov
 
PPTX
Oops in php
Gourishankar R Pujar
 
PDF
Your code sucks, let's fix it
Rafael Dohms
 
PDF
The Art of Transduction
David Stockton
 
PPT
Functional Pe(a)rls version 2
osfameron
 
PPTX
Presentation1
Rahadyan Gusti
 
Crafting beautiful software
Jorn Oomen
 
Codeware
Uri Nativ
 
Introdução ao Perl 6
garux
 
Jsphp 110312161301-phpapp02
Seri Moth
 
Doctrine fixtures
Bill Chang
 
Electrify your code with PHP Generators
Mark Baker
 
PHP and MySQL
Sanketkumar Biswas
 
PHP for Adults: Clean Code and Object Calisthenics
Guilherme Blanco
 
The History of PHPersistence
Hugo Hamon
 
Database Design Patterns
Hugo Hamon
 
PHPUnit でよりよくテストを書くために
Yuya Takeyama
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Hugo Hamon
 
The Perl6 Type System
abrummett
 
News of the Symfony2 World
Fabien Potencier
 
PHP 7 – What changed internally? (Forum PHP 2015)
Nikita Popov
 
Your code sucks, let's fix it
Rafael Dohms
 
The Art of Transduction
David Stockton
 
Functional Pe(a)rls version 2
osfameron
 
Presentation1
Rahadyan Gusti
 

Viewers also liked (20)

PPTX
Einführung in NoSQL-Datenbanken
Tobias Trelle
 
PPTX
Video games
Karitho Loaiza Osorio
 
PDF
Minnesota Business Owners' Perceptions of State and Local Regulations
Center for Rural Policy & Development
 
PPTX
Woefstok got talent - PP 2 - de eerste wedstrijd
Yvette van Veldhuijsen
 
PPTX
Blogger !!
laa_xunxa_lamejor
 
PPT
Bluetooth technology aditya
akshay8811
 
PPTX
trabajo 2 Datos
cesar82703
 
PPT
Fungi
jdrinks
 
PPT
Global warming.jasper
jasperhu
 
PDF
Rural Minnesota Journal: Why Everyone Should Care
Center for Rural Policy & Development
 
PPTX
Budget 2013
Alok Jain
 
PPTX
Goals of vocabulary learning
Karitho Loaiza Osorio
 
PDF
Rural Minnesota Journal: Where will Minnesota's Baby Boomers live in their la...
Center for Rural Policy & Development
 
PPTX
vmware optimization
Adithya Venkatesh
 
PPTX
Markma hyperanimation - del rosario
miyuuh
 
PPT
Ntl overview presentation_long
Rosalyn Alleman
 
PPTX
Vocabulary yr
jdrinks
 
PPTX
Vocabulary yr
jdrinks
 
Einführung in NoSQL-Datenbanken
Tobias Trelle
 
Minnesota Business Owners' Perceptions of State and Local Regulations
Center for Rural Policy & Development
 
Woefstok got talent - PP 2 - de eerste wedstrijd
Yvette van Veldhuijsen
 
Blogger !!
laa_xunxa_lamejor
 
Bluetooth technology aditya
akshay8811
 
trabajo 2 Datos
cesar82703
 
Fungi
jdrinks
 
Global warming.jasper
jasperhu
 
Rural Minnesota Journal: Why Everyone Should Care
Center for Rural Policy & Development
 
Budget 2013
Alok Jain
 
Goals of vocabulary learning
Karitho Loaiza Osorio
 
Rural Minnesota Journal: Where will Minnesota's Baby Boomers live in their la...
Center for Rural Policy & Development
 
vmware optimization
Adithya Venkatesh
 
Markma hyperanimation - del rosario
miyuuh
 
Ntl overview presentation_long
Rosalyn Alleman
 
Vocabulary yr
jdrinks
 
Vocabulary yr
jdrinks
 
Ad

Similar to PHP for Python Developers (20)

PDF
SPL to the Rescue - Tek 09
Elizabeth Smith
 
PDF
Using spl tools in your code
Elizabeth Smith
 
KEY
Spl Not A Bridge Too Far phpNW09
Michelangelo van Dam
 
PPTX
Generated Power: PHP 5.5 Generators
Mark Baker
 
KEY
SPL, not a bridge too far
Michelangelo van Dam
 
PPTX
Arrays in PHP
davidahaskins
 
PPTX
Looping the Loop with SPL Iterators
Mark Baker
 
PDF
잘 알려지지 않은 Php 코드 활용하기
형우 안
 
PPT
Php Chapter 2 3 Training
Chris Chubb
 
PDF
Uncovering Iterators
sdevalk
 
PDF
Iterators, ArrayAccess & Countable (Oh My!) - Madison PHP 2014
Sandy Smith
 
PPTX
Spl to the Rescue - Zendcon 09
Elizabeth Smith
 
ODP
Building and Incredible Machine with Pipelines and Generators in PHP (IPC Ber...
dantleech
 
PDF
Preparing for the next PHP version (5.6)
Damien Seguy
 
PDF
What's new in PHP 5.5
Tom Corrigan
 
PPTX
PHP Functions & Arrays
Henry Osborne
 
PDF
Spl in the wild
Elizabeth Smith
 
PDF
international PHP2011_ilia alshanetsky_Hidden Features of PHP
smueller_sandsmedia
 
ODP
Intro to The PHP SPL
Chris Tankersley
 
PPT
PHP - Introduction to PHP Arrays
Vibrant Technologies & Computers
 
SPL to the Rescue - Tek 09
Elizabeth Smith
 
Using spl tools in your code
Elizabeth Smith
 
Spl Not A Bridge Too Far phpNW09
Michelangelo van Dam
 
Generated Power: PHP 5.5 Generators
Mark Baker
 
SPL, not a bridge too far
Michelangelo van Dam
 
Arrays in PHP
davidahaskins
 
Looping the Loop with SPL Iterators
Mark Baker
 
잘 알려지지 않은 Php 코드 활용하기
형우 안
 
Php Chapter 2 3 Training
Chris Chubb
 
Uncovering Iterators
sdevalk
 
Iterators, ArrayAccess & Countable (Oh My!) - Madison PHP 2014
Sandy Smith
 
Spl to the Rescue - Zendcon 09
Elizabeth Smith
 
Building and Incredible Machine with Pipelines and Generators in PHP (IPC Ber...
dantleech
 
Preparing for the next PHP version (5.6)
Damien Seguy
 
What's new in PHP 5.5
Tom Corrigan
 
PHP Functions & Arrays
Henry Osborne
 
Spl in the wild
Elizabeth Smith
 
international PHP2011_ilia alshanetsky_Hidden Features of PHP
smueller_sandsmedia
 
Intro to The PHP SPL
Chris Tankersley
 
PHP - Introduction to PHP Arrays
Vibrant Technologies & Computers
 
Ad

Recently uploaded (20)

PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PPTX
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
PPTX
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PDF
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PPTX
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
PPTX
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PPTX
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Tally software_Introduction_Presentation
AditiBansal54083
 
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 

PHP for Python Developers

  • 1. SEMANTIC WEAPONS PHP Conf 2016 HELLO STRANGER
  • 2. SEMANTIC WEAPONS $ id -un – [email protected] – tweet me @cvences – Founded a 4yo development shop – semanticweapons.com #phpconmx
  • 3. and we’re hiring! HELLO STRANGER SEMANTIC WEAPONS
  • 4. SEMANTIC WEAPONS PHP for Python Developers
  • 5. SEMANTIC WEAPONS PHP for Python Developers Web Development & General Scripting
  • 6. SEMANTIC WEAPONS $ membership operator _ $inArray = in_array(5, range(0, 10)) === TRUE;
  • 7. SEMANTIC WEAPONS $ membership operator _ in_array = 5 in range(10) == True
  • 8. SEMANTIC WEAPONS $ membership operator _ in_array = 5 in range(10) == True >>> in_array False
  • 9. SEMANTIC WEAPONS $ default values _ # counting dictionary keys from collections import defaultdict log = ['warn', 'error', 'debug', 'info', 'warn', 'debug', 'warn'] stats = defaultdict(int) for entry in log: stats[entry] += 1
  • 10. SEMANTIC WEAPONS $ default values _ // counting elements $log = ['warn', 'error', 'debug', 'info', 'warn', 'debug', ‘warn']; $stats = []; foreach ($log as $entry){ $stats[$entry] = $stats[$entry]++ ?: 0; }
  • 11. SEMANTIC WEAPONS $ default values _ // counting elements $log = ['warn', 'error', 'debug', 'info', 'warn', 'debug', ‘warn']; $stats = []; foreach ($log as $entry){ $stats[$entry]++; }
  • 12. SEMANTIC WEAPONS $ default values _ // counting elements $log = ['warn', 'error', 'debug', 'info', 'warn', 'debug', ‘warn']; $stats = []; foreach ($log as $entry){ $stats[$entry]++; } # counting dictionary keys from collections import defaultdict log = ['warn', 'error', 'debug', 'info', 'warn', 'debug', ‘warn'] stats = defaultdict(int) for entry in log: stats[entry] += 1
  • 13. SEMANTIC WEAPONS Memory consumption – C’s pointers – SQL’s LIMIT statement – strcmp, strcpy, strcat – strncmp, strncpy, strncat – buffer overflow
  • 14. SEMANTIC WEAPONS Memory consumption – C’s pointers – SQL’s LIMIT statement – strcmp, strcpy, strcat – strncmp, strncpy, strncat – buffer overflow ¿Quién agregó la clausula LIMIT a mini SQL 1.x?
  • 15. SEMANTIC WEAPONS $ Array function myRange($max = 10) { $numeros = []; $num = 1; while ($num < $max) { array_push($numeros, $num); $num++; } return $numeros; } function sum($max = 10) { $sumatoria = 0; foreach (myRange($max) as $num) { $sumatoria += $num; } echo $sumatoria; } sum(1000000);
  • 16. SEMANTIC WEAPONS $ Iterator class NumberIter implements Iterator { private $position = 0; private $array = []; public function __construct($array = []) { $this->position = 0; $this->array = $array; } public function rewind() { $this->position = 0; } public function current() { return $this->array[$this->position]; } public function key() { return $this->position; } public function next() { ++$this->position; } public function valid() { return isset($this->array[$this->position]); } } function sum($max = 10) { $sumatoria = 0; $numberIter = new NumberIter($array = range(1, ($max - 1))); foreach ($numberIter as $num) { $sumatoria += $num; } echo $sumatoria; } sum(1000000);
  • 17. SEMANTIC WEAPONS $ PHP Arrays vs Iterators foreach (myRange($max) as $num) { $sumatoria += $num; } foreach ($numberIter as $num) { $sumatoria += $num; }
  • 19. SEMANTIC WEAPONS $ Generators function myRange($max = 10) { // $numeros = []; $num = 1; while ($num < $max) { yield $num; $num++; } // return $numeros; } function sum($max = 10) { $sumatoria = 0; foreach (myRange($max) as $num) { $sumatoria += $num; } echo $sumatoria; } sum(1000000);
  • 20. SEMANTIC WEAPONS Generators – Implement Iterators – DRY – Can traverse with foreach – foreach does not use IAP (>7.0.0) – Uses hashtable iterators now – Does not build an array in-memory – Also speeds time to generate Note: – Calling range(0, 1000000) will result in well over 100 MB of memory being used.
  • 21. SEMANTIC WEAPONS $ Iterators, Generators and Arrays class NumberIter implements Iterator { private $position = 0; private $array = []; public function __construct($array = []) { $this->position = 0; $this->array = $array; } public function rewind() { $this->position = 0; } public function current() { return $this->array[$this->position]; } public function key() { return $this->position; } public function next() { ++$this->position; } public function valid() { return isset($this->array[$this->position]); } } function myRange($max = 10) { $num = 1; while ($num < $max) { yield $num; $num++; } } array range ($start, $end, $step)
  • 22. SEMANTIC WEAPONS $ Iterators, Generators and Arrays class NumberIter implements Iterator { private $position = 0; private $array = []; public function __construct($array = []) { $this->position = 0; $this->array = $array; } public function rewind() { $this->position = 0; } public function current() { return $this->array[$this->position]; } public function key() { return $this->position; } public function next() { ++$this->position; } public function valid() { return isset($this->array[$this->position]); } } function myRange($max = 10) { $num = 1; while ($num < $max) { yield $num; $num++; } }
  • 30. SEMANTIC WEAPONS To be or not to be – Using iterators is great – foreach in 7.0.0 rocks! – lists are fat, sequences evaluate lazily – Lazy is good
  • 31. SEMANTIC WEAPONS Warning: sort() expects parameter 1 to be array, object given
  • 32. SEMANTIC WEAPONS But… – Python iterators introduced in 2.2 (2001) – range -> xrange -> range – PHP yield introduced in 5.5.0+ (2013) – Iterator name space may clash – What’s wrong with iterator_to_array? – PHP ArrayAccess Blog Post: SPL Iterators against the performance PHP Manual: /language.generators.overview.php
  • 34. SEMANTIC WEAPONS $ unpacking a list _ sum_of_numbers = sum([x**3 for x in range(10000)])
  • 35. SEMANTIC WEAPONS $ unpacking an array _ $sumOfNumbers = 0; foreach (range(1, 10000) as $num) { $sumOfNumbers += pow($num, 3); }
  • 36. SEMANTIC WEAPONS $ unpacking an array _ // second try $processArray = function($method, $array) { return array_map($method, $array); }; $sumOfNumbers = array_sum( $processArray( $method = function($x){return pow($x, 3);}, $array = range(0, 10000) ) );
  • 37. SEMANTIC WEAPONS One liners – means something in English – easy to understand at first glance
  • 38. SEMANTIC WEAPONS $ unpacking an array _ $sumOfNumbers = 0; foreach (range(1, 10000) as $value) { $sumOfNumbers += pow($value, 3); } // second try $processArray = function($method, $array) { return array_map($method, $array); }; $sumOfNumbers = array_sum( $processArray( $method = function($x){return pow($x, 3);}, $array = range(0, 10000) ) ); // third try $sumOfNumbers = array_sum(array_map(function($x){return pow($x, 3);}, range(0, 10000)));
  • 39. SEMANTIC WEAPONS $ readability _ sum_of_numbers = sum([x**3 for x in range(10000)]) $y = array_sum(array_map(function($x){return pow($x, 3);}, range(0, 10000)));
  • 40. SEMANTIC WEAPONS $ looping over two collections _ speakers = ['Javier', 'Joe', 'Rasmus', 'Carlos'] talks = ['Ansible', 'Loopless', 'Deploy', 'Python'] for speaker, talk in zip(speakers, talks): print(speaker, talk)
  • 41. SEMANTIC WEAPONS $ looping over two collections _ $speakers = ['Javier', 'Joe', 'Rasmus', 'Carlos']; $talks = ['Ansible', 'Loopless', 'Deploy', 'Python']; $max = min(count($speakers), count($talks)); foreach(range(0, $max-1) as $i){ echo($speakers[$i] .' '. $talks[$i]); }
  • 42. SEMANTIC WEAPONS $ looping over two collections _ // second approach $speakers = ['Javier', 'Joe', 'Rasmus', 'Carlos']; $talks = ['Ansible', 'Loopless', 'Deploy', 'Python']; $meetupTalks = array_combine($speakers, $talks); foreach($meetupTalks as $speaker => $talk){ echo "$speaker $talk"; }
  • 43. SEMANTIC WEAPONS $ looping over two collections _ for speaker, talk in zip(speakers, talks): print(speaker, talk) foreach(array_combine($speakers, $talks) as $speaker => $talk) echo "$speaker $talk";
  • 44. SEMANTIC WEAPONS $ python iterators magic, tweet .@cvences # dado un array asociativo, elimina todos los nombres que empiecen con la letra “c”
 meetup_info = {
 'Javier': 'Ansible',
 'Joe': 'Loopsless',
 'Rasmus': 'Deploy',
 'Carlos': 'Python',
 }
 
 meetup_info = {key: meetup_info[key] for key in meetup_info if not key.lower().startswith('c')} # dado un modelo con relationships, filtra los blogs cuyos autores tengan o no # un nombre asignado. El título no incluye la palabra python y ordénalos por fecha # de creación descendente. 
 Blog.objects .filter(entry__authors__isnull=False, entry__authors__name__isnull=True) .exclude(entry__title__icontains=‘python’) .order_by(‘-created’)
  • 45. SEMANTIC WEAPONS $ python iterators magic def fib(n):
 return (4 << n * (3 + n)) // ((4 << 2 * n) - (2 << n) - 1) & ((2 << n) - 1) def get_fibonacci_by_position(pos):
 """
 Returns the fibonacci number at pos
 
 """
 a, b = 1, 1
 
 for _ in range(pos):
 a, b = a + b, a
 
 return b