简体   繁体   中英

run a code block in php foreach even when foreach array is empty

I have a dynamic form which does insert and update at the same time. This is working well for updating existing data but it is not working when inserting data, that is because $input_fields is empty so the foreach throws an error and form fields won't show. so how do I run the code inside the foreach when $input_fields is empty?

   <?php foreach ($input_fields as $input_field) : ?>
            // some demo code below
            <div class="form-group">
                <label for="">Name</label>
                <input class="form-control field_name_input name" type="text" name="data[][name]" value="<?= $input_field['name'] ?>">
            </div>
            // some demo code below ends
   <?php endforeach; ?>

I tried below code before foreach

if(!$input_fields) {
    $input_fields = [];
}; 

and below code in foreach

foreach ((array)$input_fields as $input_field)

but that doesn't help as first code snippet is just empty array so the loop won't happen and second one is almost same thing. I hope you understand.

EDIT 1: $input_fields is an array where I saved form attributes.

Instead of an empty default array use a default entry:

if(!is_array($input_fields) || empty($input_fields)) {
    $input_fields = [
        [
            'name' => "Hubba Bubba"
            // and some more elements
        ]
    ];
}; 

Your if doesn't work because you are asking if the array is empty and then assigning it empty.

Instead of doing that you could surround your foreach loop inside the if that checks if it is empty Then it will only run if size >=1

If you want to run the loop at least once you could and empty default value or you could write the html tags inside your if block

so, I added this lines of code before foreach and It's working as I expected

if(empty($input_fields)) {
    $input_fields = [[]];
}; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM