-1

I have a constant class like so

Class MyConstants
{
const TEST = "asd";
const TEST123 = "foo";
const TEST333 = "fooBar";
const TEST321 = "bar";
}

In my controller I get all constants and select 3 at random, the problem is I only get the key from the constant but I need the value

$allConstants = $this->getAllConstants();
$foo = array_rand($allConstants, 3);

dd($foo)

 array:3 [
  0 => "TEST321"
  1 => "TES"
  2 => "TEST123"
 ]

How can i get instead the value of the constant which for example would be foobar ?

I also then need to save them to the database. Should i Loop over them ?

$fooBarEntity->setData($foo);

Thank you for your help.

MewTwo
  • 465
  • 4
  • 14
  • Possible duplicate of : [Can I get CONST's defined on a PHP class?](https://stackoverflow.com/questions/956401/can-i-get-consts-defined-on-a-php-class) – Alive to die - Anant Mar 15 '21 at 09:33

1 Answers1

0

array_flip exchanges all keys with their associated values in an array. Try this:

Class MyConstants
{
    const TEST = "asd";
    const TEST123 = "foo";
    const TEST333 = "fooBar";
    const TEST321 = "bar";
}

$reflection = new ReflectionClass(MyConstants::class);
$values = $reflection->getConstants();
$data = array_rand(array_flip($values), 3);
foreach($data as $item) {
    #$fooBarEntity->setData($item);
}
print_r($data);
Alex
  • 255
  • 2
  • 6
  • 1
    Remember to always exercise caution when using `array_flip()`, as if the same value is present multiple times in the array, every corresponding key except the last one will be lost. – Arthur Boucher Mar 15 '21 at 10:18