Skip to content

Instantly share code, notes, and snippets.

@thgs
Created December 5, 2022 13:24
Show Gist options
  • Save thgs/b0e93c0e1bd2b66fbb30639fb9ff09d0 to your computer and use it in GitHub Desktop.
Save thgs/b0e93c0e1bd2b66fbb30639fb9ff09d0 to your computer and use it in GitHub Desktop.
FlipFlop example with array_reduce
<?php
$a = range(1, 4);
$example = [1,2,3,4,5,6,3,7];
$a = $example;
print_r(array_reduce(
$a,
// (..) ==1, ==1
function ($carry, $item) {
if ($item == 1) {
$carry[] = $item;
}
return $carry;
}
));
print_r(array_reduce(
$a,
// (..) ==1, ==3
function ($carry, $item) {
static $switch = false;
if ($item == 1 || $switch === true) {
$switch = true;
}
if ($switch) {
$carry[] = $item;
}
if ($item == 3) {
$switch = false;
}
return $carry;
}
));
print_r(array_reduce(
$a,
// (...) ==1, ==1
function ($carry, $item) {
static $switch = false;
if ($item == 1 || $switch === true) {
$switch = true;
$carry[] = $item;
return $carry;
}
// condition2
elseif ($item == 1 && $switch === true) {
$switch = false;
}
return $carry;
}
));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment