1

Assuming a list like this:

   $array = array('item1', 'item2', 'item3'); // etc...

I would like to create a comma separated list like so:

implode(',', $array);

But have the added complication that I'd like to use the following logic: if the item index is a multiple of 10, use ',<br>' instead of just ',' for the separator in the implode() function.

What's the best way to do this with PHP?

I did this like so, but wonder if there's a more concise way?

function getInventory($array, $title) { 
    $list = array();
    $length = count($array);

    $i = 1;

    foreach($array as $item) {
        $quantity = $item[1];

        if(!$quantity)
            $quantity = 1;

        $item_text = $quantity . $item[3];

        if($i > 9 && ($i % 10) == 0) {
            $item_text .= ',<br>';
        } elseif($i !== $length) {
            $item_text .= ',';
        }

        $list[] = $item_text;

        $i++;
    }

    $list = implode('', $list);

    $inventory = $title . $list . '<br>';
    return $inventory;
}
1
  • 1
    Your solution looks perfectly fine to me. Commented Jun 13, 2013 at 20:37

3 Answers 3

3

This solution will work if you want to use the <br> whenever the key is divisible by 10.

implode(',', array_map(function($v, $k){ return $k%10 ? $v : '<br>' . $v; }, $array, array_keys($array)));

If instead you want every 10th element and not just the element where the key is divisible by 10, use this:

implode(',', array_map(function($v, $k){ return $k%10 ? $v : '<br>' . $v; }, $array, range(1, count($array)));

Thanks to @Jacob for this possibility.

We keep the , for the implode function and variably adjust the input array values to be prepended with a <br>.

$k%10 uses the modulus operator to return the remainder for $k divided by 10 which will be 0 when $k is a multiple of 10.

1

As long as it's not the actual array keys that you're concerned about but the position in the array (ie. the break is on every tenth element rather than every index that is a multiple of ten), then you can do it this way:

$foo = array();
for($n = 0; $n < 54; $n++) $foo[] = $n;
$parts = array_chunk($foo, 10);
for($n = 0; $n < count($parts); $n++){
    echo implode(',', $parts[$n]);
    if($n < count($parts) - 1) echo ',';
    echo "<br/>\n";
}
0
$str = '';
$array = ....;
$i = 0;
foreach($array as $index)
    $str .= $array[$index].' ,'.($index % 10 ? ' ' : '<br/>');
$str = substr($str, 0, strlen($str) - 2); // trim the last two characters ', '

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.