Patrick
Patrick

Reputation: 335

concatenate arrays with associative keys

I'll let the code speak:

$params = array();
$qtyCount = count(array(1,2,3,4,5));
$qtyAr = array(6,7,8,9,10);
$i = 1;
while($i <= $qtyCount){
  $params['quantity_'.$i] .= $qtyAr[$i];
  $i++;
}

But when I do this, the last value is missing.

BTW: the values in the qtyCount and qtyAr are bugus... just for example.

Upvotes: 0

Views: 69

Answers (2)

Rob M.
Rob M.

Reputation: 36511

I would opt for a simpler approach:

array_walk($qtyAr, function($item, $index) use (&$params) {
    $key = sprintf("quantity_%u", $index);
    $params[$key] = $item;
});

It appears that you are starting at the wrong index (1), $i should be = 0 as others have pointed out.

Upvotes: 1

Machavity
Machavity

Reputation: 31624

You're missing the last element because your unasssociated array starts with 0 and your loop starts with 1. This is why foreach works so much better because it iterates over ALL your elements.

$qtyAr = array(6,7,8,9,10);
$i = 1;
foreach($qtyAr as $val) {
    $params['quantity_' . $i] = $val;
    $i++;
}

Upvotes: 0

Related Questions