I would like a practical application of the isset()
and unset()
functions.
I'm studying PHP but I do not quite understand how this can be applied in the development of some application.
Thanks in advance.
I would like a practical application of the isset()
and unset()
functions.
I'm studying PHP but I do not quite understand how this can be applied in the development of some application.
Thanks in advance.
isset
isset
is intended to check if a variable exists or if it is not null. That being the case, isset
makes perfect sense in developing an application in PHP.
Imagine the following scenario: You need to know if a given value was passed in the url via parameter GET
. To find out if this value exists, you need to use the isset
function.
See:
if (isset($_GET['page'])) {
$page = $_GET['page'];
require __DIR__ . '/pages/' . $page . '.php';
}
In the above example, if you tried to capture the variable $_GET['page']
directly, without checking the existence of that index before, you would cause an error similar to that to be omitted if the page
was omitted in the url:
Notice: undefined index "page"
Read more at:
When do I need to use the isset?
unset
The unset
function in turn is intended to remove a variable. Its usage is less common than isset
.
It is only intended to remove a variable, so that it no longer exists.
I do not have a practical example, but you could use, for example, a variable that holds a file name that has just been deleted. If it has just been deleted, you no longer need its name.
Then
$arquivo = 'dir/nome_do_arquivo.txt';
unlink($arquivo);
unset($arquivo);