Hamz
Hamz

Reputation: 44

Trying to loop through an array key and display it

Array:

$forms = array (
    'title' => 'Form Title',
    'subtext' => 'Sub Text',
    'fields' => [
        [
            'name' => 'Question A',
            'type' => 'input',
            'placeholder' => 'Eg. Test',
            'value' => '',
            'required' => true,
            'size' => '6'
        ],
        [
            'name' => 'Question B',
            'type' => 'textarea',
            'placeholder' => 'Eg. Test',
            'value' => '',
            'required' => true,
            'size' => '6'
        ]
    ]
);

Code:

<?php
$forms_keys = array_keys($forms['fields']);
foreach ($forms_keys as $forms_key)
{
    ?>
    <div class="form-group col-md-12">
        <label for="question3"><?php echo $forms_key['name']; ?></label>
    </div>
    <?php
}
?>

Im trying to get the fields => name to display inside the label. I tried the above but cant get it working, When I echo out $forms_key, I get "0" and "1"

Upvotes: 0

Views: 59

Answers (3)

lotmasi
lotmasi

Reputation: 1

Remove the array_key and set it as below and fields is a sub array. You need to take of it also.

<?php
$forms_keys = $forms['fields'];

for ($i = 0; $i < count($forms_keys); $i++) {
    ?>
    <div class="form-group col-md-12">
        <label for="question3"><?php echo $forms_keys[$i]['name']; ?></label>
    </div>
    <?php
}
?>

Upvotes: 0

macl
macl

Reputation: 995

Your $forms['fields'] array does not have keys, it contains two array elements which contains keys for their inner elements. You can check them with $forms["fields"][0]["name"] or $forms["fields"][1]["name"].

Upvotes: 0

Martin
Martin

Reputation: 22760

From PHP Manual:

array_keys — Return all the keys or a subset of the keys of an array

You have an array of keys but no associated data as you've stripped this out. Remove array_keys from your first line:

<?php
$forms_keys = $forms['fields'];
foreach ($forms_keys as $forms_key)
{
    ?>
    <div class="form-group col-md-12">
        <label for="question3"><?php echo $forms_key['name']; ?></label>
    </div>
    <?php
}
?>

Upvotes: 2

Related Questions