Search code examples
phpgravity-forms-plugin

manual php array only returning last value


I am populating a wordpress gravity form using one of there pre render filters.

I follow their documentation normally and I dynamically populate $items[] using a foreach loop which works every time.

But this time I am not dynamically making a php foreach loop for the $items[] array, I am manually inputting each value into an array.

Please see below...

add_filter("gform_pre_render", "populate_dropdown_bike_make");
add_filter("gform_admin_pre_render", "populate_dropdown_bike_make");
function populate_dropdown_bike_make($form){
    if($form["id"] != 4)
        return $form;

    $items = array();
    $items[] = array(
        "text" => "", "value" => null,
        "text" => "YAMASAKI", "value" => "YAMASAKI",
        "text" => "YAMOTO", "value" => "YAMOTO",
        "text" => "YEZDI", "value" => "YEZDI",
        "text" => "YIBEN", "value" => "YIBEN",
        "text" => "YIYING", "value" => "YIYING",
        "text" => "YONGKANG", "value" => "YONGKANG",
        "text" => "YONGWANG", "value" => "YONGWANG",
        "text" => "ZEBRETTA", "value" => "ZEBRETTA",
        "text" => "ZENNCO", "value" => "ZENNCO",
        "text" => "ZEPII", "value" => "ZEPII",
        "text" => "ZERO-MOTORCYCLES", "value" => "ZERO-MOTORCYCLES",
        "text" => "ZEV", "value" => "ZEV",
        "text" => "ZHEJIANG", "value" => "ZHEJIANG",
        "text" => "ZHENHUA", "value" => "ZHENHUA",
        "text" => "ZHIXI", "value" => "ZHIXI",
        "text" => "ZHONGYU", "value" => "ZHONGYU",
        "text" => "ZING", "value" => "ZING",
        "text" => "ZIPPI", "value" => "ZIPPI",
        "text" => "ZIPSTAR", "value" => "ZIPSTAR",
        "text" => "ZONGSHEN", "value" => "ZONGSHEN",
        "text" => "ZONTES", "value" => "ZONTES",
        "text" => "ZUNDAPP", "value" => "ZUNDAPP"   
    );

    foreach($form["fields"] as &$field)
        if($field["id"] == 45){           
            $field["choices"] = $items;
        }

    return $form;

}


Now the problem with this is it is only returning the very last option ZUNDAPP in the dropdown.

Can anyone see why this is happening?

Thanks


Solution

  • You're redefining the same keys over and over.

    $items[] = array(
        "text" => "", "value" => null,
        "text" => "YAMASAKI", "value" => "YAMASAKI"
    )
    

    Gives:

    array(array(
        "text" => "YAMASAKI",
        "value" => "YAMASAKI"
    ));
    

    In think you intend:

    //    v-- no [] here
    $items = array(
        array("text" => "", "value" => null),
        array("text" => "YAMASAKI", "value" => "YAMASAKI"),
        // etc.