Unused line of code?


#1

What is the use of the unset($lang); statement in this code ?
What is the meaning of foreach ($langs as $lang) , what is the differnce in langs & lang


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


#2

All of these questions are answerable in the docs.


#3

I am sorry I am new here. where are the docs ?


#4

https://www.google.ca/search?q=php+docs

This is a self-directed learning site that depends upon learners doing their own background reading and study. Concepts are only introduced, not fully explored so it is up to us to expand on the 'getting our feet wet` aspect of the site.

If you still have a question after reading, then we can explore it.


#5

Thanks Roy. Sorry for if I sounded lazy there. Its just that I am trying to
face my fears of coding and dont want to repeat the mistakes that I made
earlier of not asking. Thanks again for your suggestion. Will keep that in
mind for future.

Regards

Taha Kidwai


#6

As you will have by now discovered, foreach() is a method for iterating over arrays, including associative arrays. In this instance it is an array we are iterating.

$langs as $lang

$langs is the iterable, $lang is the item at the current index.

In Ruby, we would write,

$langs.each do |$lang|

end

In Python we would write,

for $lang in $langs:

assuming we only want to look up, without mutating the list.

We could also write it this way in JavaScript. While we could write,

for (var $lang in $langs) {

}

it is not a good idea because this enumerates the object which may have added properties from someone manipulating the Array prototype object. We would normally write,

for (var $lang = 0; $lang < $langs.length; $lang++) {

}

This will iterate over the range of the array, in order.

Again, as you will have found in your reading, this is how we can remove an array element. It matters where we do this, though. If we pass an array into a function that is declared globally, and unset an element, only the local variable will be affected, not the global one we passed in. If we use the method in the global namespace, the global will be directly affected.


#7

Thanks appreciate your help.


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.