Petru Vicolas Petru Vicolas - 4 months ago 9
PHP Question

Repeat indication inside array: output that element repeatedly

I have this array (see it below) and I want to repeat each array that has a key "repeat" with a value that represents how many times to repeat.

$fields = array(
array(
'type' => 'title-wrap',
'holder' => 'h4',
'heading' => 'Test heading',
),
array(
'repeat' => 3,
'type' => 'radio',
'name' => 'specific_name',
'value' => array(
0 => 'First', // value for first repeat
1 => 'Second', // value for second repeat
2 => 'Third' // value for third repeat
),
)
);


For that I have created a recursive function named
generateForm
:

function generateForm($fields, $index = 0) {
if ( $fields == '' ) { return false; }
foreach ($fields as $field) {
if ( isset($field['type']) ) {
switch ( $field['type'] ) {
case 'title-wrap':
echo $field['heading'];
break;
case 'radio':
echo $field['value'][$index];
break;
}
}
if ( isset($field['repeat']) ) {
for ($i=0; $i < $field['repeat']-1; $i++) {
generateForm($field, $i);
}
}
}
}


The output I want:


Test heading

First

Second

Third


But I don't get the last two words in the output. What am I doing wrong?

Answer

If you want to stick with the recursive method, then you need to correct some issues:

  • The recursive call you have does not pass an array, but an element of an array. Yet the function expects an array. So you should wrap it in an array construct when passing the first argument: [$field].
  • Once the above is fixed, the test on the repeat key will succeed again when you are in a recursive call, and so you will start that loop again, and get into an endless recursion. To prevent this from happening, don't loop, but just call the function recursively for the next repetition if there is at least one more to go.

Here is the corrected code:

function generateForm($fields, $index = 0) {
    if ( $fields == '' ) { return false; }
    foreach ($fields as $field) {
        if ( isset($field['type']) ) {
            switch ( $field['type'] ) {
            case 'title-wrap':
                echo $field['heading'] . "\n";
                break;
            case 'radio':
                echo $field['value'][$index] . "\n";
                break;
            }
        }
        if ( isset($field['repeat']) && $index < $field['repeat'] - 1) {
            generateForm([$field], $index + 1);
        }
    }   
}   
Comments