Beginner PHP Tutorial – 41 – for each Statement

[ad_1]
Facebook –
GitHub –
Google+ –
LinkedIn –
reddit –
Support –
thenewboston –
Twitter –


Posted

in

by

Comments

48 responses to “Beginner PHP Tutorial – 41 – for each Statement”

  1. Nell Zappa Avatar

    i learned 2d arrays on java last sem. is this the same? elements are columns and inner elements as rows? it would be a lot more easier for me to visualize if it is.

  2. Yellow Crumb Avatar

    What the hell is up with all the variables in the foreach statement. Dizzy!

  3. Oscar 1925 Avatar

    Nice tuts,

    please a help with this one..

    array(4) { [0]=> object(stdClass)#25 (4) { ["enrolcampus"]=> string(1) "3" ["coursescode"]=> string(4) "BEED" ["studentsid"]=> string(19) "JH-NMA0000000006707" ["subjectscode"]=> string(7) "ALS 301" } [1]=> object(stdClass)#26 (4) { ["enrolcampus"]=> string(1) "3" ["coursescode"]=> string(4) "BSIT" ["studentsid"]=> string(19) "JH-IBA0000000011913" ["subjectscode"]=> string(7) "Eng 200" } [2]=> object(stdClass)#27 (4) { ["enrolcampus"]=> string(1) "3" ["coursescode"]=> string(4) "BEED" ["studentsid"]=> string(19) "JH-NMA0000000006707" ["subjectscode"]=> string(8) "Educ 201" } [3]=> object(stdClass)#28 (4) { ["enrolcampus"]=> string(1) "3" ["coursescode"]=> string(4) "BSIT" ["studentsid"]=> string(19) "JH-IBA0000000011913" ["subjectscode"]=> string(7) "Acctg 1" } }

  4. Chira Xiaolong Avatar

    what happens if you have a 3 level array? How do you echo the results? :

    $people = array ('male'=>
    array ('John', 'Tom', 'Felix'),
    'height'=> array ('170cm', '175cm', '180cm'),
    'female'=>
    array ('Jane', 'Valerie', 'Lucy'),
    'height'=> array ('170cm', '175cm', '180cm'));

  5. TheMightyWolve Avatar

    What exactly does "=>" mean in simple english

  6. Tan Chee Wei Avatar

    impressive! thanks;)

  7. sibprasad padhi Avatar

    Thanks sir. These videos are very helpfull for any biggner.
    some of the videos are not visible clearly

  8. MrLangam Avatar

    I remember having trouble with this fuckin function. Now it's easy as pie.

  9. xanScorp Avatar

    Doesn't work when I attempt to apply the same principle to another PHP file. And my instructors are useless pieces of crap.

  10. soduno Avatar

    Man – I never realised it would be that simple. Thanks a million!

  11. hXcFreethinker Avatar

    Seems like a lot of people are having trouble with this one. Let me see if I can shed some light.

    Here is our multi dimensional array:
    $food = array('HEALTHY' =>
         array('salad', 'vegetables', 'pasta'),
    'UNHEALTHY' =>
         array('pizza', 'ice cream', 'popcorn'));

    To simplify, think of this as a table where the first array $food is the headings and the inner arrays are the columns under the headings:
    HEALTHY     UNHEALTHY     <- $food array
    salad            pizza
    vegetables    ice cream          <- inner arrays
    pasta            popcorn

    Now to access our data we use a foreach loop. Remember that the first foreach loop will only be able to access the data in the first array($food). Since we have more arrays nested inside our first array we will also need a nested foreach loop to access the remaining data.

    If we do the following:
    foreach($food as $element){
         echo $element;
    }
    we get: HEALTHY and UNHEALTHY as our output.
    Remember that HEALTHY and UNHEALTHY are both associative arrays and they contain arrays themselves. To access the values in these arrays we need a variable that represents the array stored within the $food array.

    We must change our foreach loop from above to look like this:
    foreach($food as $element => $inner-array){}
    Now we have the variable $inner_array which stores the array inside of the $food array. Lets say that the variable $element is equal to HEALTHY. the $inner_array variable stores the following:
    array('salad', 'vegetables', 'pasta')

    if we were to ignore the initial foreach loop and pretend we have just made the $inner_array as a regular associative array we would access its data with another foreach loop:
    foreach($inner_array as $item){
         echo $item;
    }
    Now we put this loop inside our original loop so we can access every element of $food and every element of $element.

    The entire process can be described as:
    1. the first foreach loop runs and accesses the first element of $food ('HEALTHY'), which is stored in $element ($element = 'HEALTHY') it also assigns the array containing all the healthy food to $inner_element ($inner_element = array('salad', 'vegetables', 'pasta') ) so it can be accessed by the nested foreach loop.

    2. The nested foreach loop accesses the first element of $inner_array and assigns it to $item ($item = 'salad'). This foreach loop will continue to output the rest of the elements in $inner_array until it has done them all. Once finished the nested loop will terminate or stop.

    3. Since the nested loop stopped we now hit the bottom brace of the first loop. The first loop has not finished looping through all of its elements yet so it starts over. It now accesses the second element of $food ('UNHEALTHY') and again stores it in $element ($element = 'UNHEALTHY'). $inner_array is now set to the array stored inside UNHEALTHY ($inner_array = array('pizza', 'ice cream', 'popcorn')).

    4. The nested foreach loop does the exact same thing as in step 2 but with the UNHEALTHY items.

    5. both loops are done as they have now reached the end off all available arrays and all the data has been outputted to the screen.

    Again think of it like the table above. We are basically telling the computer to read a heading then list all of the items under that heading. Once you have listed all the items look for another heading and again list off all the items under that heading.
    Now that the computer knows how to read out the data of any table, we can add headings or items and it will still know how to read them all back to us!

    I really hope this helps those of you who are struggling with this concept. Just remember and array like this is essentially just a table and the foreach loops tell the computer how to read from the table.

  12. Mark Rayne Avatar

    first of all love the videos been watching them since episode one  and appreciate the time,

    but I must say as a person who knows programming languages at an intermediate level this is not a very good explanation,you should have tried to address also how the array and their elements are stored in memory it would not have  confused people as much.some of your tuts are great some not so well explained.

    just as an example you skipped over why you were assigning $inner_array to $element and how it worked,basically you were just showing the syntax without explaining it that's why people are confused on this video.

  13. Liam Mackle Avatar

    "Further access our inner elements" Sounds like some kind of eastern philosophy out of context.

  14. V. Peters Avatar

    <?php

    $food = array('Healthy' =>
                                array('Salad', 'Vegetable', 'Pasta'),
                    'Unhealthy' =>
                                array('pizza', 'ice cream', 'popcorn'));

    foreach($food as $element => $inner_array) {
        echo '<strong>'.$element.'</strong><br>';
        foreach($inner_array as $item){
            echo $item.'<br>';
        }
    }

    ?>

  15. kid kaito Avatar

    I didn't understand !!!!!

  16. alexander shekhtman Avatar

    This is much better code:

    <?

    $food = array(
            'Healthy'=>array('Pasta'=>300, 'Salad'=>150, 'Vegetables'=>150),
            'Unhealthy'=>array('Pizza'=>1000, 'Ice Cream'=>2000) );
            

    foreach($food as $categories => $category){
    foreach($category as $item => $calories){
    echo "$item" . " is " . "$categories" . " and has a calorie value of " . "$calories <br>";
    }
    }

    ?>

    And here is the output:

    Pasta is Healthy and has a calorie value of 300 
    Salad is Healthy and has a calorie value of 150 
    Vegetables is Healthy and has a calorie value of 150 
    Pizza is Unhealthy and has a calorie value of 1000 
    Ice Cream is Unhealthy and has a calorie value of 2000 

    Why would you want a multi dimensional array? To make a board game. To store a table of data. And they can have mixed datatypes so you could have columns as keys and values and rows as entries. 

    And technical you can have three dimensions and make a cube. You could make a Rubics Cube game, but then you would need to keep track of which one has two colors and which as three and figure out how to move each side and when the game is finished. 

  17. Gianluca Murru Avatar

    maybe this example is more simple:

    <?php

       $character = array("Mickey", "Donald", "Pluto");
       
       foreach($character as $name) {

            echo "$name <br>";
    }
    ?>

    in your browser you will obtain:
    Mickey
    Donald
    Pluto

    now, let's add $animal

    <?php

       $character = array("Mickey"=>"mouse", "Donald"=>"duck", "Pluto"=>"dog");
       
       foreach($character as $name => $animal) {

            echo "$name is a $animal. <br>";
    }
    ?>

    you'll obtain:

    Mickey is a mouse.
    Donald is a duck.
    Pluto is a dog.

  18. Gianluca Murru Avatar

    mmh… I don't get it this time…

  19. King Trawal Avatar

    you don't explain things well.  just sayin

  20. Jared Cubilla Avatar

    lol rounded brackets

  21. Zhenhao Zhou Avatar

    wow 1hour and 10 minute ads

  22. Jeehoo Ahn Avatar

    yea idk why you choose to do a multidimensional array when you're just introducing the foreach statement.

  23. Pogi Ako Avatar

    This video………so awesome! 😀

  24. Mike Smith Avatar

    Aint you got no learning boy? ^IGGER!!

  25. Paul Elam Avatar

    You know your stuff Alex, but these video will be much better if you practice writing the code BEFORE you do the tutorial. Great programmer, but you need improvement teaching what you know.

  26. TheKurtPrice Avatar

    Turn off error reporting.

  27. Mr. Neko Avatar

    I have notice that says, "Notice: Array to string conversion in C:xampphtdocsbostonforeach.php on line 11
    Array"

    How do I get rid of this?

  28. zanpaktuh Avatar

    JIIIHHHHAAAADDD!!!

  29. smosherx Avatar

    does this mean you cant have a variable named $element ?

  30. Nathan McBride Avatar

    well maybe the year apprenticeship helped 😛

  31. Faustodc Avatar

    lol seriously? and only by watching his 200 vids? :O

  32. Nathan McBride Avatar

    started watching your tutorials about a year ago, now I have a job in web development! cheers man!

  33. Sumit Ghulyani Avatar

    ur tutorials are soo awesm mann ….i LIKE dem frst now…watch later … 😀 😛

  34. slayer0273 Avatar

    I had trouble figuring this out, until I thought about how it's similar to some of the commands in SQL. Thanks for these videos, mate! I've learned more than I thought I could in such a short time.

  35. Ahmad Umair Avatar

    Yar aap pedaishi pagal ho ya ab hogai ho? 😉

  36. TheThugart Avatar

    its more simple than lynda.com phpmysql tutorial !!!!!!!!!!!!

  37. Novica Vukobratovic Avatar

    9.999 viewer ! Give me my free IPad

  38. c4stoners Avatar

    always sorta got confused on arrays with any programming language, this helped a lot

  39. Pr3fixProducts Avatar

    You just slept on my cock

  40. Reaction Avatar

    really nice tutorials Alex , keep going

  41. Nahiyan Alamgir Avatar

    I like all your videos Alex, you did a great job!

  42. Dalwanaage Avatar

    Thank you very much, Alex and Thenewboston for sharing your knowledge with us.

Leave a Reply

Your email address will not be published. Required fields are marked *