calling array

Discussion in 'PHP' started by roice, Dec 8, 2010.

  1. #1
    Hello,
    I build array:

    $sites_menu_dropdown = array(
    "green.php" => 'green',
    "red.php" => 'red',
    "blue.php" => 'blue',
    "orange.php" => 'orange',
    "yellow.php" => 'yellow',
    );

    now I need to build loop that will print the page name (i.e: green.php) and name (i.e: green) for the first 3 cells (must be in loop).
    How can I do that?

    Thank you in advance
     
    roice, Dec 8, 2010 IP
  2. s_ruben

    s_ruben Active Member

    Messages:
    735
    Likes Received:
    26
    Best Answers:
    1
    Trophy Points:
    78
    #2
    Try this:

    
    $sites_menu_dropdown = array(
    "green.php" => 'green',
    "red.php" => 'red',
    "blue.php" => 'blue',
    "orange.php" => 'orange',
    "yellow.php" => 'yellow',
    );
    
    $n = 0;
    
    foreach($sites_menu_dropdown as $key => $value){
        if($n>=3){ return; }
        echo("<p>".$key." - ".$value."</p>");
        $n++;
    }
    
    PHP:
     
    s_ruben, Dec 8, 2010 IP
  3. roice

    roice Peon

    Messages:
    200
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks
    Why did you use "return"?
     
    roice, Dec 8, 2010 IP
  4. s_ruben

    s_ruben Active Member

    Messages:
    735
    Likes Received:
    26
    Best Answers:
    1
    Trophy Points:
    78
    #4
    And why not? :) Use what you want to break the loop.
     
    s_ruben, Dec 8, 2010 IP
  5. plog

    plog Peon

    Messages:
    298
    Likes Received:
    11
    Best Answers:
    1
    Trophy Points:
    0
    #5
    You only want the first 3 elements. A foreach loop will run until its out of elements. So to break that loop he included that statement so that only 3 elements will be processed.
     
    plog, Dec 8, 2010 IP
  6. roice

    roice Peon

    Messages:
    200
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    putting "return;" in "foreach" loop will breake the loop?
     
    roice, Dec 11, 2010 IP
  7. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    52
    Best Answers:
    33
    Trophy Points:
    150
    #7
    The use of return is not advised in this situation as it will stop executing any code after that loop and return a void to the parent application if any. Instead, use break:

    
    $sites_menu_dropdown = array(
    "green.php" => 'green',
    "red.php" => 'red',
    "blue.php" => 'blue',
    "orange.php" => 'orange',
    "yellow.php" => 'yellow',
    );
    
    $n = 0;
    
    foreach($sites_menu_dropdown as $key => $value){
        if($n>=3){ break;}
        echo("<p>".$key." - ".$value."</p>");
        $n++;
    }
    
    PHP:
     
    ThePHPMaster, Dec 11, 2010 IP