Use variable as key name in php

I am trying to fill an array with subarrays in a loop. Each iteration should have array_push and after the loop I want to save the array. The array should look like this:

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 key name is variable. So, "pa_attribute1," pa_attribute2 ", etc. are the result of a function, and I" don't know "the result, so I can't program all possibilities. Is there a function available that I can use to create a new array with a variable as a key ? Like this?

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

    $value = get_attribute_name();

    $value = Array();

    array_push($result, [array]);
}

print_r($result);

      

+3


source to share


1 answer


You don't need to array_push()

, you can add elements directly:



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

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

}

      

+4


source







All Articles