0

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.

3
  • 1
    Insert it inside of another loop, maybe? Commented Sep 27, 2019 at 18:24
  • 5
    Multiple times in different places? You could create a function. Commented Sep 27, 2019 at 18:27
  • A function seems to be the best option indeed. Thanks @Don't Panic Commented Sep 28, 2019 at 6:29

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

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.