php

How to delete a variable in PHP

There are three ways to delete defined variables in PHP:

  • unset($var)
  • $var = (unset)$var
  • $var = null

Only the first of these ways actually deletes the variable completely. The other two, set it to NULL, which means that the variable no longer has a value, but in principle still exists. Accessing this would not generate the error “variable does not exist”.
 

Example: “unset($var)” vs “(unset)$var” vs “$var = null”

In this example the variables $var1, $var2 and $var3 are defined identically.
 
[st_adsense]  

<?php
    // Defining sample variables
    $var1 = 'variable 1';
    $var2 = 'variable 2';
    $var3 = 'variable 3';
     
    // Output the three variables before deleting
    var_dump($var1, $var2, $var3);
     
    // Delete variables
    unset($var1);
    $var2 = (unset)$var2;
    $var3 = null;
     
    // Output variables after deleting
    // var1 should get an error because it was completely deleted
    var_dump($var1, $var2, $var3);
     
    // List all currently available variables
    var_dump(get_defined_vars());
?>

Output:

string(10) "variable 1"
string(10) "variable 2"
string(10) "variable 3"


Notice:  Undefined variable: var1 in [...][...] on line 17
NULL
NULL
NULL

array(6) {
  ["_GET"]=>
  array(0) {
  }
  ["_POST"]=>
  array(0) {
  }
  ["_COOKIE"]=>
  array(0) {
  }
  ["_FILES"]=>
  array(0) {
  }
  ["var2"]=>
  NULL
  ["var3"]=>
  NULL
}
PHP MCQ - Multiple Choice Questions and AnswersPHP Questions and Answers – Object-Oriented OOP – Part 1This collection of PHP Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “Object-Oriented OOP”.   1. The concept of…Read More [st_adsense] mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *