• The unlink () and unset () functions are used to do some undo operations but used in different situations because both acts differently.

unlink () function

  • In PHP unlink () function is used when you want to delete the files completely and it is an inbuilt function.
  • In this the filename of the file which has to be deleted is sent as a parameter and True on success and False on failure when the function returns.
  • The unlink () function accepts two parameters in PHP they are filename and context.
  • The filename is a mandatory parameter which specifies the filename of the file which has to be deleted.
  • The context is an optional parameter which specifies the context of the file handle which can be used to modify the nature of the stream.
  • Suppose there is a file named ‘gfg.txt’, it returns True on success and False on failure.

Sample Code

<?php

// PHP program to delete a file named gfg.txt
// using unlink() function

$file_pointer = fopen('gfg.txt');

// Writing on a file named gfg.txt
fwrite($file_pointer, 'A computer science portal for Wikitechy!');
fclose($file_pointer);

// Using unlink() function to delete a file
unlink('gfg.txt');

?>

Output

unset () function

  • The unset () function is used when you want to make that file empty and it is an inbuilt function which is used to remove the content from the file by emptying it in PHP.
  • Thereby making it empty, the unset () function not only clears the file content but also is used to unset a variable.
  • It means that the function clears the content of a file rather deleting it.
  • This function accepts single parameter variable which is required and it does not return any value.

Sample Code

<?php

$var = "hello";

// Change would be reflected outside the function
function unset_value() {
unset($GLOBALS['var']);
}

unset_value();
echo $var;
?>

Output

Categorized in: