Getting fields by label [RESOLVED]

I am working on a function to find a field from any form based on the label text. I’d like to return different attributes of the field so that I can use them later.

Originally, I just needed the value of the field, so I used the work here to return the value of a field based on the label:

function itsg_get_value_by_label( $form, $entry, $label ) {
            foreach ( $form['fields'] as $field ) {
                $lead_key = $field->label;
                if ( strToLower( $lead_key ) == strToLower( $label ) ) {
                    return $entry[ $field->id ];
                }
            }
            return false;
        }

I get my value by setting a variable and passing in the field label that I’m looking for:

$mobile_phone = itsg_get_value_by_label( $form, $entry, "Mobile Phone" );

Later on, as I continued to work on my solution, I found that I also needed to find those fields and return the ID. Initially, I wrote the same function and just returned the ID, but I’d like to make the solution more efficient by rewriting the function to return multiple field attributes in an array, as such:

function get_field_atts_by_label( $form, $entry, $label ) {
            foreach ( $form['fields'] as $field ) {
                $lead_key = $field->label;
                if ( strToLower( $lead_key ) == strToLower( $label ) ) {
                    $field_atts = array(
                        'value' => $entry[ $field->id ],
                        'id'    => $field->id,
                    );
                    return $field_atts;
                }
            }
            return false;
        }

My problem now is that I am not quite sure how to retrieve the specific attributes from my function and set them to a variable. I’m hoping someone will help me finish this off.

Basing on what you’re returning with your function, that’d be something like this:

$field = get_field_atts_by_label( $form, $entry, 'Mobile Phone' );

if ( false !== $field )
{
    $value = $field['value'];
    $id = $field['id'];
}

2 Likes

Ahh, yes. Duh! So simple. Thanks!