PHP array with various elements (e.g. Python set)

Is there a version of the PHP array class where all elements must be different, for example, in Python?

+3
source share
7 answers

Nope. You can fake it using an associative array, where the keys are elements in the "set" and the values ​​are ignored.

+4
source

Here is the first draft of an idea that can ultimately work for what you want.

<?php

class DistinctArray implements IteratorAggregate, Countable, ArrayAccess
{
    protected $store = array();

    public function __construct(array $initialValues)
    {
        foreach ($initialValues as $key => $value) {
            $this[$key] = $value;
        }
    }

    final public function offsetSet( $offset, $value )
    {
        if (in_array($value, $this->store, true)) {
            throw new DomainException('Values must be unique!');
        }

        if (null === $offset) {
            array_push($this->store, $value);
        } else {
            $this->store[$offset] = $value;
        }
    }

    final public function offsetGet($offset)
    {
        return $this->store[$offset];
    }

    final public function offsetExists($offset)
    {
        return array_key_exists($offset, $this->store);
    }

    final public function offsetUnset($offset)
    {
        unset( $this->store[$offset] );
    }

    final public function count()
    {
        return count($this->store);
    }

    final public function getIterator()
    {
        return new ArrayIterator($this->store);
    }
}

$test = new DistinctArray(array(
    'test' => 1,
    'foo'  => 2,
    'bar'  => 3,
    'baz'  => '1',
    8      => 4,
));

try {
    $test[] = 5;
    $test[] = 6;
    $test['dupe'] = 1;
}
catch (DomainException $e) {
  echo "Oops! ", $e->getMessage(), "<hr>";
}

foreach ($test as $value) {
    echo $value, '<br>';
}
+4
source

array_unique .

+2

- , yo -. . , , , array_unique

+1

, : SplObjectStorage

The SplObjectStorage class provides a map from objects to data or, ignoring data, a set of objects.

+1
source

In the main case, you can try array_unique(), perhaps this will help to avoid duplicates in your array.

0
source

You can use this Install class . You can install with pecl

sudo pecl install ds

there is also a polyfill version if you do not have root access

composer require php-ds/php-ds
0
source

Source: https://habr.com/ru/post/1713259/


All Articles