Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two arrays in foreach loop

I want to generate a selectbox using two arrays, one containing the country codes and another containing the country names.

This is an example:

<?php     $codes = array('tn','us','fr');     $names = array('Tunisia','United States','France');      foreach( $codes as $code and $names as $name ) {         echo '<option value="' . $code . '">' . $name . '</option>';     } ?> 

This method didn't work for me. Any suggestions?

like image 864
medk Avatar asked Dec 18 '10 23:12

medk


People also ask

Can we use two foreach loop in PHP?

Note − If there are more than 2 arrays, nested 'foreach' loops can be used. Here, 2 arrays have been declared and they are being traversed using the 'foreach' loop. The result is that the respective index of every array is matched and the data at those indices are displayed one next to the other.

Can you nest forEach loops?

The nesting operator: %:% An important feature of foreach is the %:% operator. I call this the nesting operator because it is used to create nested foreach loops. Like the %do% and %dopar% operators, it is a binary operator, but it operates on two foreach objects.

Can we use foreach loop for array in Java?

In this tutorial, we will learn about the Java for-each loop and its difference with for loop with the help of examples. In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList). It is also known as the enhanced for loop.

Does forEach work on arrays?

The forEach method is also used to loop through arrays, but it uses a function differently than the classic "for loop". The forEach method passes a callback function for each element of an array together with the following parameters: Current Value (required) - The value of the current array element.


1 Answers

foreach( $codes as $code and $names as $name ) { } 

That is not valid.

You probably want something like this...

foreach( $codes as $index => $code ) {    echo '<option value="' . $code . '">' . $names[$index] . '</option>'; } 

Alternatively, it'd be much easier to make the codes the key of your $names array...

$names = array(    'tn' => 'Tunisia',    'us' => 'United States',    ... ); 
like image 74
alex Avatar answered Sep 30 '22 10:09

alex