Practical application of isset() and unset() in PHP

Asked

Viewed 1,424 times

2

I would like a practical application of the functions isset() and unset(). I’m studying PHP but I don’t understand very well how this can be applied in the development of some application.

From now on, thank you.

1 answer

4


isset

isset is intended to verify if a variable exists or if it is not null. Being so, isset makes perfect sense in developing a PHP application.

Imagine the following scenario: You need to know if a certain value was passed in the url, via parameter GET. To know if this value exists, you need to use the function isset.

Behold:

if (isset($_GET['page'])) {
   $page = $_GET['page'];
   require __DIR__ . '/pages/' . $page . '.php';
}

In the example above, if you tried to capture the variable $_GET['page'] directly, without first verifying the existence of that index, you would make that, if it was omitted in the url the value page, an error similar to that:

Notice: Undefined index "page"

Read more on:

When isset is required?

unset

The function unset in turn aims to remove a variable. Its use is less common than the isset.

It aims only to remove a variable, causing it to cease to exist.

I don’t have a practical example, but you could use for example in a variable that stores a name of a file that has just been deleted. If he’s just deleted, you don’t need his name anymore.

So

 $arquivo = 'dir/nome_do_arquivo.txt';

 unlink($arquivo);

 unset($arquivo);
  • 1

    Thank you so much, Wallace. You’ve been very helpful!!! :)

  • Count on us for whatever you need

Browser other questions tagged

You are not signed in. Login or sign up in order to post.