Skip to content

Instantly share code, notes, and snippets.

@ziadoz
Last active July 3, 2023 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ziadoz/4710a96bd0dd3039da53c790aeac8877 to your computer and use it in GitHub Desktop.
Save ziadoz/4710a96bd0dd3039da53c790aeac8877 to your computer and use it in GitHub Desktop.
PHP Enum Next/Previous Case
<?php
enum Foo: string
{
case A = 'A';
case B = 'B';
case C = 'C';
public function next(): self
{
if ($this === self::cases()[count(self::cases()) - 1]) {
return $this;
}
return self::cases()[array_search($this, self::cases()) + 1];
}
public function prev(): self
{
if ($this === self::cases()[0]) {
return $this;
}
return self::cases()[array_search($this, self::cases()) - 1];
}
}
print_r(Foo::cases());
print_r(array_search(Foo::C, Foo::cases(), true));
print_r(Foo::A->next()->next()->next());
print_r(Foo::C->prev()->prev()->prev());
print_r(Foo::B->next()->prev());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment