Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ligonsker's avatar

Factory - randomElement based on other randomElement result

if I want a factory to choose randomElement from an array, based on the previous result:

'unit' => fake()->randomElement(['A', 'B', 'C', 'D', 'E']),
'sub_unit' => // in case of 'A', select randomElement from array that belongs to 'A'.. etc

Is there a convenient way, or I will somehow need to create a function that gets the previous result?

0 likes
4 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Put it in a variable that can be used to resolve sub_unit

$unit = fake()->randomElement(['A', 'B', 'C', 'D', 'E']);
1 like
Ligonsker's avatar

@Sinnbeck done, looks like it's working:

    public function definition()
    {
        $unit_arr = ['A', 'B', 'C', 'D', 'E'];
        $subunit_arr = [
            'A' => ['A_A','A_B', 'A_C', 'A_D', 'A_E'],
            'B' => ['B_A','B_B', 'B_C', 'B_D', 'B_E'],
            'C' => ['C_A','C_B', 'C_C', 'C_D', 'C_E'],
            'D' => ['D_A','D_B', 'D_C', 'D_D', 'D_E'],
            'E' => ['E_A','E_B', 'E_C', 'E_D', 'E_E']        
        ];

        $unit = fake()->randomElement($unit_arr);
        $subunit = fake()->randomElement($subunit_arr[$unit]);
         

        return [
            'unit' => $unit,
            'subunit' => $subunit,
       ];

Ty!

Please or to participate in this conversation.