Durian Nangka
Durian Nangka

Reputation: 255

How to efficiently repeat a block of PHP code including a loop?

I would like to repeat the following code 15 times or more on a single page:

$html .= '<select name="select_product_category" 
class="dropdown_list"><option value="0">All 
categories</option>';

foreach($categories as $value)  {

$html .= '<option value="' . $value['category_id'] . 
'"';

if($value['category_id'] === $active_category_id) 
$html .= ' checked';

$html .= '>' . $value['category_name'] . '</option>';

}

$html .= '</select>';

Is there a better way to achieve this than just repeat this particular block of code? Thanks for your support.

Upvotes: 0

Views: 468

Answers (1)

Pavol Velky
Pavol Velky

Reputation: 810

Try to use functions as suggested by @Don't Panic

<?php

    function generateSelectBoxHTML() 
    {
        $html = '<select name="select_product_category" class="dropdown_list"><option value="0">All categories</option>';
        foreach ($categories as $category) {
            $checked = '';
            if ($category['category_id'] === $activeCategoryId) {       
                $checked = ' checked="checked"';
            }

            $html .= sprintf('<option value="%s"%s>%s</option>', $category['category_id'], $checked, $category['category_name']);
        }

        $html .= '</select>';
        return $html;
    }

    $html .= generateSelectBoxHTML();
    // ...
    $html .= generateSelectBoxHTML();
    $html .= generateSelectBoxHTML();
    $html .= generateSelectBoxHTML();

Upvotes: 1

Related Questions