Create a gist now

Instantly share code, notes, and snippets.

Avoiding ifs
<?php
/**
* EXAMPLE 1
*/
//with if
if ($gender === 'male') {
return 'Hello sexy man!';
}
if ($gender === 'female') {
return 'Hey sexy!';
}
//without if
$greetings = ['male' => 'Hello sexy man!', 'female' => 'Hey sexy!'];
return $greetings[$gender];
/**
* EXAMPLE 2
*/
//with if
$people = ['Andrei', 'Jon', 'Charlie'];
$guests = [];
foreach($people as $guy) {
if (in_array($guy, ['Andrei', 'Charlie'])) {
$guests[] = $guy;
}
}
var_dump($guests);
//without if
$guests = new Guests($people);
foreach ($guests as $guest) {
echo $guest;
}
class Guests implements \IteratorAggregate
{
private $people = [];
/**
* @var \CallbackFilterIterator
*/
private $iterator;
public function __construct(array $people)
{
$this->people = $people;
$this->iterator = new \CallbackFilterIterator(
new \ArrayIterator($people),
function ($guy) {
return in_array($guy, ['Andrei', 'Charlie']);
});
}
public function getIterator()
{
return new \IteratorIterator($this->iterator);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment