3

This is my enum class. I want a random value every time from this enum class. I am using the PHP 8.1 enum feature.

<?php>

declare(strict_types=1);
namespace App\Enums;

enum Division: string
{
    case BARISAL = 'barisal';
    case CHITTAGONG = 'chittagong';
    case DHAKA = 'dhaka';
    case KHULNA = 'khulna';
    case RAJSHAHI = 'rajshahi';
    case RANGPUR = 'rangpur';
    case MYMENSINGH = 'mymensing';
    case SYLHET = 'sylhet';
}
<?php>
4
  • Duplicate?: stackoverflow.com/a/18168360/9636400 Commented Sep 22, 2022 at 6:52
  • 2
    Get the value listing as array, and pick a random element from that? php.net/manual/en/language.enumerations.listing.php Commented Sep 22, 2022 at 6:53
  • $divisions = Division::cases(); $randomDivision = $divisions[rand(0, count($divisions))]; Commented Sep 12, 2023 at 20:35
  • 1
    Division::cases()[rand(0, count(Division::cases())-1)] Commented Jan 28, 2024 at 11:38

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.