0

In Java we got a special for-loop to read from arrays:

for (char c : a)
System.out.print(c + " ");

Every element of the array a will be saved in the variable c. The variable c will be unavailable after the loop is finished. This can be used to output easily every element of the array.

Does this special for-loop exist in PHP? I wasn't able to find it in the PHP docs and in the Google results.

CodeShark
  • 1,709
  • 2
  • 14
  • 22
  • yes there is such a thing in php, `foreach` you may need to manually unset `$c` afterwards – Kevin Nov 05 '14 at 07:51
  • It may be worth noting that PHP "arrays" are really HashMaps where the key just happens to be an integer. All answers here are functionally the same, but the implementation is very different. More explained **[here](http://stackoverflow.com/questions/2350361/how-is-the-php-array-implemented-on-the-c-level)** – asontu Nov 05 '14 at 08:09

2 Answers2

2

Well, there is of course the foreach manual

You can do

foreach($a as $c){
    echo $c;
}

The variable $c however will be available after the loop! You can obviously call unset is you really need it to be gone.

Nanne
  • 64,065
  • 16
  • 119
  • 163
  • I'm not sure if this is the same as the Java for-loop example above. After thinking about it I think it is the same. I will try this in some examples and test if it will end in the same result. // Thanks for your edit. This is an important difference then. – CodeShark Nov 05 '14 at 07:52
  • It iterates over `$a` and puts all values in `$c`. That's what it does. Not too complicated I think? – Nanne Nov 05 '14 at 07:54
  • Yes you are right about that part. I forgot that it's as simple as that in PHP. I just heard it in the university and I wasn't able to remember that fast how it was done in PHP. I think the only difference is as you said that the variable c will exist. It may be important to know in some specific cases. For example if you try to write to c. – CodeShark Nov 05 '14 at 07:59
1

Try this:

foreach ($a as $c) {
    echo $c . " ";
}
unset($c);
echo "c after loop: $c"; //$c returns nothing
biko
  • 510
  • 6
  • 15
  • Note that this solution unsets the variable $c, making it unavailable as per your request :) – biko Nov 08 '14 at 02:07