0

I have arrays of Strings(that are each a combination of numbers "1" to "20") inside another array in PHP. I want to pre-tick the corresponding checkboxes (1 - 20) for each of my pages (these start at 0 and go on for potentially very many).This way the user can go to a page and see which boxes have been selected before.

For example:
Array [0] is {1, 2, 4} so these checkboxes should be checked when the user arrives at page 0.

This is what I have so far to try and get the values of the inner array:

foreach ($categoriesArr as $val) {
    if (is_array($val)) {
        foreach ($val as $innerVal) {
            // See which checkboxes are checked.
            if ($innerVal === "1") {
                $cb1 = true;
            } else {
                $cb1 = false;
            }
        }
    }
}

I know I can use <?php if ($cb1) echo "checked" ?> in the checkbox HTML to show it as ticked.
This is ok but it obviously loops through all the arrays and $cb1 will eventually end up as whatever the last arrays value is.
Should I introduce yet another array to store each individual pages checkbox values in? I am potentially dealing with thousands of entries so would like to keep any extra assignments to a minimum.

4
  • Off topic but is $innerVal a string? Else $cb1 is always false because of the === operator. Commented Nov 10, 2014 at 15:20
  • $innerVal is indeed a String sir, question ammended to reflect that Commented Nov 10, 2014 at 15:22
  • Could you elaborate on what informations you want to have after the foreach? Checkboxes checked on each page seperatly? Checkboxes checked on all pages combined? Commented Nov 10, 2014 at 15:27
  • I want the user to be able to see which checkboxes have been pre-selected for each page, on each page, so page 2 may have different boxes from page 4 for example. Commented Nov 10, 2014 at 15:30

1 Answer 1

1

I would suggest to have variable that holds page's index, and then you just include this into each checkbox: <?php if(is_array($categoriesArr[$pageIndexVariable]) && $categoriesArr[$pageIndexVariable][$checkboxNameOrIdOrwhatever]) echo "checked" ?>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I realise how simple this is now. I think I was making life hard for myself but I can finish this now :)

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.