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
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:
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.
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: