NVO
NVO

Reputation: 2703

Use a variable as key name in php

I'm trying to fill an array with subarrays in a loop. In each iteration there must be an array_push, and after the loop I want save the array. The array must be looks as follows:

Array => (
    "pa_attribute1" => Array(
         'name' => 'pa_attribute1',
         'value' => 'value',
         'is_visible' => '1',
         'is_taxonomy' => '1'
    ),
    "pa_attribute2" => Array(
         'name' => 'pa_attribute2',
         'value' => 'value',
         'is_visible' => '1',
         'is_taxonomy' => '1'
    ),
    "pa_attribute3" => Array(
         'name' => 'pa_attribute3',
         'value' => 'value',
         'is_visible' => '1',
         'is_taxonomy' => '1'
    ),
)

The 'problem' is, that the name of key is a variable. So, "pa_attribute1, "pa_attribute2" and so on, are the result of a function, and I 'don't know' the result, so I can't program all the possibilities. Is there a function available what I can use to create an new array with a variable as key? Like this?

$result = array();
for($i=0; $1 < $length; $i++){

    $value = get_attribute_name();

    $value = Array();

    array_push($result, [array]);
}

print_r($result);

Upvotes: 3

Views: 2142

Answers (1)

jeroen
jeroen

Reputation: 91734

You don't need array_push(), you can add elements directly:

for($i=0; $i < $length; $i++){

    $result[get_attribute_name()] = [array];

}

Upvotes: 4

Related Questions