phparrayaccess

The offset parameter will be set to NULL if another value is not available what does it mean in php?


I am learning to ArrayAccess interface for my final year project. I don't know when the offset parameter of the ArrayAccess::offsetSet() is set to NULL. As stated in the php.net.

Note: The offset parameter will be set to NULL if another value is not available, like in the following example.

<?php
$arrayaccess[] = "first value";
$arrayaccess[] = "second value";
print_r($arrayaccess);
?>

The above example will output:

Array
(
    [0] => first value
    [1] => second value
)

So what is the concept of NULL here ? Can anyone tell ?

Reference Link http://php.net/manual/en/arrayaccess.offsetset.php.

Thanks !


Solution

  • You mentioned ArrayAccess, this is interface, and if you implement that in your class - you will be able to use your class as array.

    You copied sentence from manual about offsetSet method

    Note: The offset parameter will be set to NULL if another value is not available, like in the following example.

    Example is not really correct there, so I prepare another one:

    http://sandbox.onlinephpfunctions.com/code/baedfadc9bd6bbfbde5ef7152e8c4e7d4a1d99e2

    output is:

    this is MyTest::offsetSet offset: NULL; value: 'first value'
    this is MyTest::offsetSet offset: NULL; value: 'second value'
    

    You can see that offset parameter is NULL if you do not set it in the code, however if you use code like that:

    $arrayOffset[3] = "third value";

    offset parameter will be 3

    UPDATE: Answering on your question:

    No. If you want to support both, insertion, and updating. You should implement this logic in offsetSet method. e.g:

    public function offsetSet($offset, $value)
    {
        if (is_null($offset)) {
            $this->data[] = $value;
        } else {
            $this->data[$offset] = $value;
        }
    }