phparraysforeachunset

Why do I need unset $value after foreach loop


I am playing around with arrays in PHP, and I've get confused about unset() function, here's the code:

<?php

$array = array(1, 2, 3, 4);
foreach ($array as $value) {
    $value + 10;
}
unset($value);
print_r($array);

?>

Is it necessary to unset($value), when $value remains after foreach loop, is it good practice?


Solution

  • There's no need to use unset in the current context that you are using it. unset will simply destroy the variable and its content.

    In the example you are giving, this is looping through an array creating $value, then you are unsetting that variable. Which means it no longer exists in that code. So that does absolutely nothing.

    To visuallize what I am talking about look at this example:

    $value = 'Hello World';
    echo $value;
    unset($value);
    echo $value;
    

    The following out will be:

    Hello World<br /><b>NOTICE</b> Undefined variable: value on line number 6<br />
    

    So you will first see the Hello World, but after unsetting that variable trying to call it will just cause an error.

    To answer your question, you really don't have to unset value; there's no need for it. As the foreach loop is setting a $value of each array() + 10.

    Unsetting it will cause the work to be removed, and forgotten.