Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

ArrayAccess

The interface of objects accessed with square brackets.

Syntax

class Name implements ArrayAccess

Return value

ArrayAccessThe `offsetExists()`, `offsetGet()`, `offsetSet()` and `offsetUnset()` methods.

Examples

Settings accessed like an array:

<?php
 
class Config implements ArrayAccess
{
    private array $data = ['theme' => 'light'];
 
    public function offsetExists(mixed $key): bool { return isset($this->data[$key]); }
    public function offsetGet(mixed $key): mixed { return $this->data[$key] ?? null; }
    public function offsetSet(mixed $key, mixed $value): void { $this->data[$key] = $value; }
    public function offsetUnset(mixed $key): void { unset($this->data[$key]); }
}
 
$config = new Config();
$config['size'] = 14;
 
echo $config['theme'], ' ', $config['size'], ' ';
var_dump(isset($config['lang']));

Output:

light 14 bool(false)

Notes

Brackets do not make the object an array: array_map(), in_array() and count() do not accept it.

See also

  • ArrayObject — An object that behaves like an array.
  • Countable — The interface of objects that can be passed to `count()`.
  • isset — Checks that a variable exists and is not null.

In the tutorial

  • Built-in interfaces — PHP interfaces that teach an object to behave like an array — Countable, IteratorAggregate, ArrayAccess, JsonSerializable and Stringable.

Thanks for reading!

Donate to the site — we work hard for you.