0

In my cart class I have a loop:

foreach($this->items as $key => $item) {
    $duplicate = clone $item;
    $duplicate->price = 0;
    $duplicate->dynamic = 1;
    // Duplicate new item to cart
    $this->AddItem($duplicate, $key+1);
}

Over in the AddItem function it does this: array_splice($this->items, $position, 0, array($newItem));

And it works, but the problem is the items are not going in the place I want them too. This is going to be tricky to explain but hopefully someone can understand.

So lets say for example the $items array is made up of: array('a', 'b', 'c', 'd')

I end up with:

array('a', 'a2', 'b2', 'c2', 'b', 'c', 'd')

But what I want is: array('a', 'a2', 'b', 'b2', 'c', 'c2', 'd')

Because the $key value is not changing within the foreach loop, it inserts it into the position $key of the old $this->items array. But I want the new items to be duplicated after their original counterparts. I hope this makes sense.

2
  • @ProfessorAbronsius $this->items is an array of class type CartItems Commented Feb 23, 2021 at 8:43
  • just FYI - from the PHP manual - " If replacement is not an array, it will be typecast to one (i.e. (array) $replacement). This may result in unexpected behavior when using an object or NULL replacement. " Commented Feb 23, 2021 at 9:02

1 Answer 1

2

You can use an additional variable to store the number of dupes to increase the index.

$dupes = 0;
foreach ($this->items as $key => $item) {
    $duplicate = clone $item;
    $duplicate->price = 0;
    $duplicate->dynamic = 1;
    // Duplicate new item to cart
    $this->AddItem($duplicate, $key + 1 + $dupes);
    $dupes++;
}

See a live example

class Test 
{
    private $items = ['a','b','c','d'];

    public function dup()
    {
        $dupes = 0;
        foreach ($this->items as $key => $item) {
            $this->addItem($item . '2', $key + 1 + $dupes);
            $dupes++;
        }
    }

    private function addItem($newItem, $position) 
    {
        array_splice($this->items, $position, 0, array($newItem));  
    } 

    public function dump() 
    {
        var_dump($this->items);
    }

}


$test = new Test();
$test->dup();
$test->dump();

Output :

array(8) {
  [0]=>
  string(1) "a"
  [1]=>
  string(2) "a2"
  [2]=>
  string(1) "b"
  [3]=>
  string(2) "b2"
  [4]=>
  string(1) "c"
  [5]=>
  string(2) "c2"
  [6]=>
  string(1) "d"
  [7]=>
  string(2) "d2"
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is really simple and clever. Thanks!

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.