so imma noob

foreach is a control structure used in many languages. I want to learn how to use it in PHP, but I think I’m too dumb.

Anyone care to explain it to me? All of the reading I’ve done online doesn’t make sense. It hasn’t clicked.

So now I’m doing this:

$arr_count = count($arr);
for($i=0; $i
// loopy
}

PS: Here’s my favorite Halloween costume.
PPS: I hate slow mailservers and ColdFusion.

Advertisements

About andyhillky
I'm cool.

2 Responses to so imma noob

  1. rick says:

    Okay… so foreach… very useful.

    There are two ways to use foreach as far as I can tell:

    foreach ($arr as $value) {
    echo htmlspecialchars($value);
    }

    The above code would just safely print to the web-browser each of the elements of the array.

    foreach ($arr as $key => $value) {
    echo htmlspecialchars($key) . “: ” . htmlspecialchars($value);
    }

    Again, this code just loops through and this time prints the keys and values (for use with associative arrays) separated by a colon and a space.

    Using the for loop as you are currently is most likely either equivalent or better computationally. With foreach, it has to check if there is another element to deal with, whereas with your version, you tell it up front how many iterations to expect. I’m not sure the difference exists or if it does, is significant.

    There is another way to do it, and I think it is likely to be just about the same as the other two ways:

    while ($element = each($arr) {
    echo htmlspecialchars($element[‘value’]);
    }

    Just another thought. Again, computationally I’m not really sure that any of them are significantly better than the others. I do hope this helped clear things up a little bit. If not, you know you can hit me up on MSN.

  2. stevo says:

    Yeah, the foreach is a fun one… I’ll add a little on to anonymous’ explanation.

    Say you have an array you want to go through and add a ‘1’ on the end of each value. You can:

    $array[‘blue’] = ‘color’;
    $array[‘square’] = ‘shape’;

    foreach ($array as $key => $value) {
    $array[$key] = $value . ‘1’;
    }

    Where $key is either the value “blue” or “square” and $value is either “color” or “shape” respectively.

    PHP5 has a nice little feature so you don’t have to use the $key => $value setup (I’ll stick with the $array above):

    foreach ($array as &$value) {
    $value = $value . ‘1’;
    }

    Which will add a “1” to the end of each like our first foreach, but in a different way. The & can be used on functions too to use the actual variable rather than creating a new instance for that function.

    function test (&$variable) {
    $variable = ‘yes’;
    }

    $variable = ‘no’;
    test($variable);

    echo $variable; // will return “yes”

    Hope that adds to the fun.

%d bloggers like this: