Skip to content

After an element is removed from a collection or set, the indices do not shift #133

@antonowano

Description

@antonowano

Description

Removing elements from a collection is done using the standard PHP function unset(). Therefore, the array indexes are lost. This leads to incorrect operation in some cases. One such case is JSON serialization.
Implementing deletion using the array_splice function would correct this situation.

public function remove(mixed $element): bool
{
    if (($position = array_search($element, $this->data, true)) !== false) {
        unset($this[$position]);

        return true;
    }

    return false;
}

Steps to reproduce

use Ramsey\Collection\Collection;

$collection = new Collection('int', [1, 2, 3]);
var_dump(json_encode($collection->toArray())); // '[1,2,3]'
$collection->remove(2);
var_dump(json_encode($collection->toArray())); // '{"0":1,"2":3}'

Expected behavior

I expected it to be '[1,3]' after deletion.

Environment details

  • version of this package: 2.1.1
  • PHP version: 8.4
  • OS: Windows 11

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions