Skip to content

Instantly share code, notes, and snippets.

@asrorbekh
Created June 11, 2024 11:19
Show Gist options
  • Save asrorbekh/bd3682f4fcd163fc5ecef5dc79e10e0e to your computer and use it in GitHub Desktop.
Save asrorbekh/bd3682f4fcd163fc5ecef5dc79e10e0e to your computer and use it in GitHub Desktop.
<?php
class Map
{
private array $container = [];
public function __construct(array $data = [], $keyField = null)
{
if (!empty($data) && $keyField !== null) {
$this->setMultiple($data, $keyField);
}
}
public function set($key, $value): void
{
$this->container[$key] = $value;
}
public function get($key)
{
return $this->container[$key] ?? null;
}
public function has($key): bool
{
return array_key_exists($key, $this->container);
}
public function delete($key): bool
{
if ($this->has($key)) {
unset($this->container[$key]);
return true;
}
return false;
}
public function clear(): void
{
$this->container = [];
}
public function size(): int
{
return count($this->container);
}
public function entries(): array
{
return $this->container;
}
private function setMultiple(array $array, $keyField): void
{
$this->container = array_column($array, null, $keyField);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment