Note that even though isset/empty works on classes implementing ArrayAccess, array_key_exists does not. At least not in PHP 5.3.
(PHP 5, PHP 7)
ArrayAccess::offsetExists — Whether an offset exists
Whether or not an offset exists.
This method is executed when using isset() or empty() on objects implementing ArrayAccess.
Note:
When using empty() ArrayAccess::offsetGet() will be called and checked if empty only if ArrayAccess::offsetExists() returns
TRUE
.
offset
An offset to check for.
Returns TRUE
on success or FALSE
on failure.
Note:
The return value will be casted to boolean if non-boolean was returned.
Example #1 ArrayAccess::offsetExists() example
<?php
class obj implements arrayaccess {
public function offsetSet($offset, $value) {
var_dump(__METHOD__);
}
public function offsetExists($var) {
var_dump(__METHOD__);
if ($var == "foobar") {
return true;
}
return false;
}
public function offsetUnset($var) {
var_dump(__METHOD__);
}
public function offsetGet($var) {
var_dump(__METHOD__);
return "value";
}
}
$obj = new obj;
echo "Runs obj::offsetExists()\n";
var_dump(isset($obj["foobar"]));
echo "\nRuns obj::offsetExists() and obj::offsetGet()\n";
var_dump(empty($obj["foobar"]));
echo "\nRuns obj::offsetExists(), *not* obj:offsetGet() as there is nothing to get\n";
var_dump(empty($obj["foobaz"]));
?>
The above example will output something similar to:
Runs obj::offsetExists() string(17) "obj::offsetExists" bool(true) Runs obj::offsetExists() and obj::offsetGet() string(17) "obj::offsetExists" string(14) "obj::offsetGet" bool(false) Runs obj::offsetExists(), *not* obj:offsetGet() as there is nothing to get string(17) "obj::offsetExists" bool(true)
Note that even though isset/empty works on classes implementing ArrayAccess, array_key_exists does not. At least not in PHP 5.3.
If you care about key-strictness, you may need to use an alternative solution (maybe overriding offsetExists() in subclass(es)). So, offsetExists() acts like array_key_exists() and does not handle the key types. Here;
<?php
$array = ['one', 'two', 3.=>'boom!'];
$arrayObject = new ArrayObject($array);
$key = '3';
var_dump(array_key_exists($key, $array)); // bool(true)
var_dump(in_array($key, array_keys($array), true)); // bool(false)
var_dump($arrayObject->offsetExists($key)); // bool(true)
var_dump(in_array($key, array_keys($arrayObject->getArrayCopy()), true)); // bool(false)
// @override;
public function offsetExists($key)
{
// make a strict check
return in_array($key, array_keys($this->getArrayCopy()), true);
}
?>