Skip to content

Instantly share code, notes, and snippets.

@jawira
Last active June 20, 2019 08:27
Show Gist options
  • Save jawira/3cd0806bc75a9da7ae0c to your computer and use it in GitHub Desktop.
Save jawira/3cd0806bc75a9da7ae0c to your computer and use it in GitHub Desktop.
Testing PHP7 features with Fibonacci sequence function
<?php
/**
* Succinct Fibonacci function
*
* Returns the first N Fibonacci numbers specified as parameter.
*
* This function has not been written for efficiency nor readabilty, instead it has
* been created for fun and for testing the latest PHP features (E.g.: generators,
* literal dereferencing, type hinting, short array syntax, ...).
*
* Function tested on PHP 7.0.0beta3.
*
* @author Jawira Portugal
* @param int $q
* @return \Generator
*/
function fibonacci(int $q = 0b1): Generator {
for ($_ = [-1, 1]; 0 < $q; --$q)
yield (list($_[0], $_[1]) = [$_[1], array_sum($_)])[1];
}
// Printing the first 5 Fibonacci numbers
foreach(fibonacci(5) as $num) {
echo $num, PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment