1

So I am working on a JQuery Step Form. It is being populated with dynamic information from the database. I have a particular list of items that is 21 items in the array. I would like to break these down into groups of 5 or 6 per step, so the form isn't so long.

I know I could use array_slice for example, but since this list is dynamic, I don't know how many there will always be. It will kind of be paginated in a sense but I don't need pagination links and such. Just a way to return 5 items, then 5 items and if the last iteration only has 2 items then that is it.

So for example:

$array = ( 
  array(
    "name" => "Peter Parker",
    "alterego" => "Spiderman",
  ),
  array(
    "name" => "Clark Kent",
    "alterego" => "Superman",
  ), 
  array(
    "name" => "Bruce Wayne",
    "alterego" => "Batman",
  ),
);

And then I want to break this down to only list 2 items per group.

2
  • 2
    Array_chunk? php.net/manual/en/function.array-chunk.php Commented May 27, 2019 at 3:08
  • Yes @Andreas, this is correct. I mentioned you in the answer below. Commented May 27, 2019 at 3:34

2 Answers 2

1

You can use array_chunk for example:

$chunks = array_chunk($array, 5);
foreach ($chunks as $chunk) {
    // display form for these 5 values
}
Sign up to request clarification or add additional context in comments.

Comments

0

Andreas' initial advice is great. Maybe here, we might want to design some callback functions based on the pagination sizes that we wish to have:

array_slice($array, getChunkStart($array), getChunkLength($array));

or if we just look for a specific column size:

array_chunk($array, sizeof(array_column($array, "column_key")));

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.