CKTIS / PHP
Keyword unset
Remove a variable binding or array entry.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
unset($row["name"], $alias);Remove a variable binding or array entry. Unsetting an alias leaves the value accessible through any other reference. Removing a numeric array key does not renumber the survivors, and a later append uses the next available automatic index, which can leave gaps. An inaccessible property may invoke __unset(). An ordinary writable typed property becomes uninitialized after unset. Unsetting an initialized readonly property from an ordinary method of its own class raises Error.
$n=2; $alias=&$n; unset($alias); $row=["a","b"]; unset($row[0]); $row[]="c"; echo json_encode([$n,array_keys($row)]);
class Box {public int $n=2;private $hidden;public function __unset($k){echo $k," ";}} $o=new Box(); echo "\n";unset($o->hidden,$o->n);try{echo $o->n;}catch(Error $e){echo get_class($e);}
class Fixed { public function __construct(public readonly int $n){} public function clear(){unset($this->n);} } $f=new Fixed(4); try{$f->clear();}catch(Error $e){echo "\n",get_class($e)," ",$f->n;}
[2,[1,2]]
hidden Error
Error 4
Examples
<?php
$n=2; $alias=&$n; unset($alias); $row=["a","b"]; unset($row[0]); $row[]="c"; echo json_encode([$n,array_keys($row)]);
class Box {public int $n=2;private $hidden;public function __unset($k){echo $k," ";}} $o=new Box(); echo "\n";unset($o->hidden,$o->n);try{echo $o->n;}catch(Error $e){echo get_class($e);}
class Fixed { public function __construct(public readonly int $n){} public function clear(){unset($this->n);} } $f=new Fixed(4); try{$f->clear();}catch(Error $e){echo "\n",get_class($e)," ",$f->n;}
Result
[2,[1,2]] hidden Error Error 4