1

I have the following arrays

$meta_boxes[] = array(
    'id' => 'measurements',
    'title' => 'Measurements',
    'fields' => array(  
        array(
            'name' => 'Select Units of Measurement',
            'id' => 'units',
            'type' => 'radio',
            'options' => array(
                array('name' => 'Pounds', 'value' => 'Pounds'),
                array('name' => 'Kilos', 'value' => 'Kilos'),
                array('name' => 'Ton', 'value' => 'Ton'),
                array('name' => 'Short Ton', 'value' => 'Short Ton')
            )
        ),      
        array(
            'name' => 'Displacement',
            'id' => 'displacement',
            'type' => 'text',
            'std' => ''
        ),
        array(
            'name' => 'Gross Tonnage',
            'id' => 'gross_tonnage',
            'type' => 'text',
            'std' => ''
        )
      )
)

//more meta_boxes[] arrays continued...

When using a foreach loop to get elements from arrays in the fields array how can I omit one array? For example omit looping through the first array in 'fields' with id = units ? Or any other array for that matter.

foreach ($meta_boxes as $metabox) {
    foreach ( $metabox['fields'] as $field ) {      
        echo $field['name']; //field name       
    }      
}

2 Answers 2

2

Use the keyword continue together with an if condition to continue with the next entity in your loop.

To skip more than one $field with a specific id I recommend this

foreach ($meta_boxes as $metabox) {
    foreach ( $metabox['fields'] as $field ) {      
        if (in_array ($field['id'], array ('units', 'gross_tonnage'))
            continue;

        echo $field['name']; //field name       
    }      
}

If it's only one use something as this:

foreach ($meta_boxes as $metabox) {
    foreach ( $metabox['fields'] as $field ) {      
        if ($field['id'] == 'units')
            continue;

        echo $field['name']; //field name       
    }      
}

Documentation of the keyword continue.

Sign up to request clarification or add additional context in comments.

Comments

2
foreach ($meta_boxes as $metabox) {
    foreach ( $metabox['fields'] as $field ) {      
        if ($field['id'] == 'units') continue;
        echo $field['name']; //field name       
    }      
}

Continue keyword documentation

1 Comment

Thank you! continue seems to be very efficient.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.