user319940
user319940

Reputation: 3317

Dynamically populate a subarray inside of an array declaration

I'm trying to create an array inside an array, using a for loop - here's my code:

array(
    'label' => 'Assign to user',
    'desc' => 'Choose a user',
    'id' => $prefix . 'client',
    'type' => 'radio'
    'options' => array( 
        foreach ($clients as $user) {
         $user->user_login => array (  
            'label' => $user->user_login,  
            'value' => $user->user_login,
            ), 
        }
    )
)

Unfortunately this gives me a

"Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ')'"

For the line:

'options' => array( 

I'm at a bit of a loss as to what has gone wrong. $clients is defined elsewhere, so that is not the problem.

Upvotes: 15

Views: 32793

Answers (4)

mickmackusa
mickmackusa

Reputation: 47873

array_map() will elegantly allow you to dynamically populate the subarray without needing to break out of tour original array. Demo

$result = [
    'label' => 'Assign to user',
    'desc' => 'Choose a user',
    'id' => $prefix . 'client',
    'type' => 'radio',
    'options' => array_map( 
        fn($user) => [  
            'label' => $user->user_login,  
            'value' => $user->user_login,
        ], 
        $clients
    )
];

Upvotes: 0

Marc B
Marc B

Reputation: 360572

That's invalid syntax. You'd have to build the "parent" portions of the array first. THEN add in the sub-array stuff with the foreach loop:

$foo = array(
    'label' => 'Assign to user',
    'desc' => 'Choose a user',
    'id' => $prefix.'client',
    'type' => 'radio',
    'options' => array()
);

foreach ($clients as $user) {
    $foo['options'][] = array (  
        'label' => $user->user_login,  
        'value' => $user->user_login,
    );
}

Upvotes: 26

Cody Covey
Cody Covey

Reputation: 1060

You cannot use the foreach in the definition of the array. You can however put the $clients variable in the array itself or you can foreach outside the array to build the array to be inserted at the options key

Upvotes: 1

ste
ste

Reputation: 306

You use foreach to access the data, not define it.

Try this:

array(
    'label' => 'Assign to user',
    'desc' => 'Choose a user',
    'id' => $prefix.'client',
    'type' => 'radio'
    'options' => $clients
    )

If you need to change the structure of the data for 'options', do this before defining the primary array.

Upvotes: 2

Related Questions