What does the unset($lang); do in this lesson?


#1

When I delete or manipulate it, nothing appears to change. I thought "unset" what used to remove something from an array, is it not? Could you please explain unset easily if you can? Thank you!

    <?php
      $langs = array("JavaScript",
      "HTML/CSS", "PHP",
      "Python", "Ruby");
    
      foreach ($langs as $lang) {
          echo "<li>$lang</li>";
      }
    
      unset($lang);
    ?>

#2

Yes, unset can remove the whole array or just the array element.

At first you created array with a few items in it. And then listed each one using foreach loop. Array items still will be displayed in the browser because you listed them first and only after that you used unset.

If you want to see effect just try putting unset($langs); before foreach loop and the whole array will be removed. In your case unset($lang); isn't correct because $lang variable is only relevant in foreach loop and that's where it only exists. If you want to remove first element of the array then this will do just that: unset($langs[0]); to delete any item that exists in that array you have to specify existing element index.


#3

Thank you for this great answer! Codecademy added that unset line into this. It's there from the beginning of the lesson and it doesn't have you do anything with it. That's why it was so confusing to me, because I couldn't figure out why they added it when it appears to not do anything. It made me backtrack to the unset lesson to see if I missed something, but I couldn't find anything I missed, so I posted here.

Your answer definitely helps me understand unset better, thank you!


#4

Glad it helped :slightly_smiling: If you want to find out how value changed after certain operations in variable just echo out that variable or for variables that hold arrays use print_r($langs); function it will show you what items you have.