Back to Basics: For Each Loops in PHP and Other Languages

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Back to Basics: For Each Loops in PHP and Other Languages

    I'm going to use real-world examples where foreach loops are used specifically in PHP, but the same concepts apply in pretty much every programming language out there.

    What are For Each Loops used for?
    For Each Loops are a kind of conditional loop in every programming language that allows you to iterate over array values in an array. Here's an example using the PHP programming language:

    PHP Code:
    $get_poll_votes $this->db->get_where("poll_votes",$where_votes);

    foreach(
    $get_poll_votes->result() as $result)
    {
        switch(
    $result->vote_option)
        {
            case 
    "option_1":
            
    $data['votes'][1]++;
            break;

            case 
    "option_2":
            
    $data['votes'][2]++;
            break;

            case 
    "option_3":
            
    $data['votes'][3]++;
            break;

            case 
    "option_4":
            
    $data['votes'][4]++;
            break;

            case 
    "option_5":
            
    $data['votes'][5]++;
            break;

            case 
    "option_6":
            
    $data['votes'][6]++;
            break;

            case 
    "option_7":
            
    $data['votes'][7]++;
            break;

            case 
    "option_8":
            
    $data['votes'][8]++;
            break;

            case 
    "option_9":
            
    $data['votes'][9]++;
            break;

            case 
    "option_10":
            
    $data['votes'][10]++;
            break;
        }

    In this example, the get_where() method returns a resultset from a MySQL query. To iterate over each result, you have to loop through the result() method. The resulting row from the loop is in the $result variable (hence as $result). I am then checking what the value is of a specific row that is returned from the query using a switch statement (also may be referred to as a select statement in other languages). A switch statement is essentially a more optimised if statement.

    The foreach() loop will continue as long as there are rows to go through that was returned from the MySQL query executed by the get_where() method.

    What is a "method"?
    A method is similar to a standalone function but is a conceptual name that is part of object-oriented programming. While beginners do not need to understand what object-oriented programming is, object-oriented programming can help to create more organised, readable and extensible application code. If you want to learn more, you can read more about object-oriented programming in our Explanation of object-oriented programming concepts and features article.
Working...
X