Asked  7 Months ago    Answers:  5   Viewed   41 times

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?

 Answers

74
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',
   ...
);
Wednesday, March 31, 2021
 
jerrygarciuh
answered 7 Months ago
24

Something like this should work:

$count = count($data['product']);
for ($i = 0; $i < $count; $i ++) {
    echo $data['product'][$i] . ' ' . $data['date'][$i] . ' ' .$data['time'][$i] . '<br />';
}

To add data-verification/integrity to it (to stop undefined index errors), also check if each index exists in the sub-arrays:

$count = count($data['product']);
for ($i = 0; $i < $count; $i++) {
    $date = isset($data['date'][$i]) ? ' ' . $data['date'][$i] : '';
    $time = isset($data['time '][$i]) ? ' ' . $data['time '][$i] : '';
    echo $data['product'][$i] . $date . $time . '<br />';
}
Wednesday, March 31, 2021
 
aaronhuisinga
answered 7 Months ago
97

Use the second parameter forEach accepts instead, which will be the current index you're iterating over:

n = [1,2,3,5,7,8,9,11,12,13,14,16,17,18,20,21,22];

n.forEach((element, index) => {
  console.log(element, index);
});

If you have two separate arrays to begin with, in each iteration, access the [index] property of the other array:

var n = [1, 2, 3, 5, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 20, 21, 22];
var m = [0, 1, 2, 3, 4, 5, 6, 7,  8,  9,  10, 11, 12, 13, 14, 15, 16];

n.forEach((num1, index) => {
  const num2 = m[index];
  console.log(num1, num2);
});
Wednesday, June 9, 2021
 
sassy_geekette
answered 5 Months ago
52

You need to iterate the elements from the inside array, like this:

foreach($resultArray as $row => $innerArray){
  foreach($innerArray as $innerRow => $value){
    echo $value . "<br/>";
  }
}
Wednesday, August 4, 2021
 
Cam1989
answered 3 Months ago
25

Do you mean something like:

foreach($_POST['something'] as $key => $something) { 
    $example = $_POST['example'][$key];
    $query = mysql_query("INSERT INTO table (row, row2) VALUES ('{$something}','{$example}')"); 
} 
Wednesday, August 11, 2021
 
PeanutsMcgee
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :