Can i nest a foreach within foreach? - php

I have an array: $categories = array("item1", "item2", "item3");
I also have three arrays: $item1Array = array("hi", "items");, $item2Array = array("hi", "items");, $item3Array = array("hi", "items");
I stated a foreach like this:
foreach ($categories as &$value) {
echo "<optgroup label='" . $value . "'>';
$nextArray = $value . "Array";
foreach($nextArray as &$nextValue) {
echo "<option value='" . $nextValue . "'>" . $nextValue . "</option>";
}
}
but it get an error Warning: invalid argument supplied for foreach().
Is there a way I can achieve this?

Yes, you could, by ${$nextArray}. but notice named variables is not good practice, you could use associative array instead.
And note you don't need to use reference in this case.
$categories = array("item1", "item2", "item3");
$item1Array = array("hi", "items");
$item2Array = array("hi", "items");
$item3Array = array("hi", "items");
foreach ($categories as $value) {
echo "<optgroup label='" . $value . "'>";
$nextArray = $value . "Array";
foreach(${$nextArray} as $nextValue) {
echo "<option value='" . $nextValue . "'>" . $nextValue . "</option>";
}
}

Of course, but as you can clearly see from the syntax highlighting of your post, you used a ' instead of a " at the end of the "optgroup" line.
Also, you could just use a nested array:
$categories = Array(
"item1"=>Array("hi","items"),
"item2"=>Array("hi","items"),
"item3"=>Array("hi","items"),
);
foreach($categories as $key=>$array) {
echo "<optgroup label='".$key."'>";
foreach($array as $value) {
echo "<option>".$value."</option>";
}
echo "</optgroup>";
}

Related

Using Nested foreach Loops in PHP [duplicate]

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?
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',
...
);
foreach operates on only one array at a time.
The way your array is structured, you can array_combine() them into an array of key-value pairs then foreach that single array:
foreach (array_combine($codes, $names) as $code => $name) {
echo '<option value="' . $code . '">' . $name . '</option>';
}
Or as seen in the other answers, you can hardcode an associative array instead.
Use array_combine() to fuse the arrays together and iterate over the result.
$countries = array_combine($codes, $names);
array_map seems good for this too
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
array_map(function ($code, $name) {
echo '<option value="' . $code . '">' . $name . '</option>';
}, $codes, $names);
Other benefits are:
If one array is shorter than the other, the callback receive null values to fill in the gap.
You can use more than 2 arrays to iterate through.
Use an associative array:
$code_names = array(
'tn' => 'Tunisia',
'us' => 'United States',
'fr' => 'France');
foreach($code_names as $code => $name) {
//...
}
I believe that using an associative array is the most sensible approach as opposed to using array_combine() because once you have an associative array, you can simply use array_keys() or array_values() to get exactly the same array you had before.
This worked for me:
$codes = array('tn', 'us', 'fr');
$names = array('Tunisia', 'United States', 'France');
foreach($codes as $key => $value) {
echo "Code is: " . $codes[$key] . " - " . "and Name: " . $names[$key] . "<br>";
}
Your code like this is incorrect as foreach only for single array:
<?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>';
}
?>
Alternative, Change to this:
<?php
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
$count = 0;
foreach($codes as $code) {
echo '<option value="' . $code . '">' . $names[count] . '</option>';
$count++;
}
?>
Why not just consolidate into a multi-dimensional associative array? Seems like you are going about this wrong:
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
becomes:
$dropdown = array('tn' => 'Tunisia', 'us' => 'United States', 'fr' => 'France');
You can use array_merge to combine two arrays and then iterate over them.
$array1 = array("foo" => "bar");
$array2 = array("hello" => "world");
$both_arrays = array_merge((array)$array1, (array)$array2);
print_r($both_arrays);
All fully tested
3 ways to create a dynamic dropdown from an array.
This will create a dropdown menu from an array and automatically assign its respective value.
Method #1 (Normal Array)
<?php
$names = array('tn'=>'Tunisia','us'=>'United States','fr'=>'France');
echo '<select name="countries">';
foreach($names AS $let=>$word){
echo '<option value="'.$let.'">'.$word.'</option>';
}
echo '</select>';
?>
Method #2 (Normal Array)
<select name="countries">
<?php
$countries = array('tn'=> "Tunisia", "us"=>'United States',"fr"=>'France');
foreach($countries as $select=>$country_name){
echo '<option value="' . $select . '">' . $country_name . '</option>';
}
?>
</select>
Method #3 (Associative Array)
<?php
$my_array = array(
'tn' => 'Tunisia',
'us' => 'United States',
'fr' => 'France'
);
echo '<select name="countries">';
echo '<option value="none">Select...</option>';
foreach ($my_array as $k => $v) {
echo '<option value="' . $k . '">' . $v . '</option>';
}
echo '</select>';
?>
Walk it out...
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
PHP 5.3+
array_walk($codes, function ($code,$key) use ($names) {
echo '<option value="' . $code . '">' . $names[$key] . '</option>';
});
Before PHP 5.3
array_walk($codes, function ($code,$key,$names){
echo '<option value="' . $code . '">' . $names[$key] . '</option>';
},$names);
or combine
array_walk(array_combine($codes,$names), function ($name,$code){
echo '<option value="' . $code . '">' . $name . '</option>';
})
in select
array_walk(array_combine($codes,$names), function ($name,$code){
#$opts = '<option value="' . $code . '">' . $name . '</option>';
})
echo "<select>$opts</select>";
demo
<?php
$codes = array ('tn','us','fr');
$names = array ('Tunisia','United States','France');
echo '<table>';
foreach(array_keys($codes) as $i) {
echo '<tr><td>';
echo ($i + 1);
echo '</td><td>';
echo $codes[$i];
echo '</td><td>';
echo $names[$i];
echo '</td></tr>';
}
echo '</table>';
?>
foreach only works with a single array. To step through multiple arrays, it's better to use the each() function in a while loop:
while(($code = each($codes)) && ($name = each($names))) {
echo '<option value="' . $code['value'] . '">' . $name['value'] . '</option>';
}
each() returns information about the current key and value of the array and increments the internal pointer by one, or returns false if it has reached the end of the array. This code would not be dependent upon the two arrays having identical keys or having the same sort of elements. The loop terminates when one of the two arrays is finished.
Instead of foreach loop, try this (only when your arrays have same length).
$number = COUNT($_POST["codes "]);//count how many arrays available
if($number > 0)
{
for($i=0; $i<$number; $i++)//loop thru each arrays
{
$codes =$_POST['codes'][$i];
$names =$_POST['names'][$i];
//ur code in here
}
}
array_combine() worked great for me while combining $_POST multiple values from multiple form inputs in an attempt to update products quantities in a shopping cart.
I think that you can do something like:
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
foreach ($codes as $key => $code) {
echo '<option value="' . $code . '">' . $names[$key] . '</option>';
}
It should also work for associative arrays.
I think the simplest way is just to use the for loop this way:
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
for($i = 0; $i < sizeof($codes); $i++){
echo '<option value="' . $codes[$i] . '">' . $names[$i] . '</option>';
}
if(isset($_POST['doors'])=== true){
$doors = $_POST['doors'];
}else{$doors = 0;}
if(isset($_POST['windows'])=== true){
$windows = $_POST['windows'];
}else{$windows = 0;}
foreach($doors as $a => $b){
Now you can use $a for each array....
$doors[$a]
$windows[$a]
....
}
I solved a problem like yours by this way:
foreach(array_keys($idarr) as $i) {
echo "Student ID: ".$idarr[$i]."<br />";
echo "Present: ".$presentarr[$i]."<br />";
echo "Reason: ".$reasonarr[$i]."<br />";
echo "Mark: ".$markarr[$i]."<br />";
}
You should try this for the putting 2 array in singlr foreach loop
Suppose i have 2 Array
1.$item_nm
2.$item_qty
`<?php $i=1; ?>
<table><tr><td>Sr.No</td> <td>item_nm</td> <td>item_qty</td> </tr>
#foreach (array_combine($item_nm, $item_qty) as $item_nm => $item_qty)
<tr>
<td> $i++ </td>
<td> $item_nm </td>
<td> $item_qty </td>
</tr></table>
#endforeach `
Few arrays can also be iterated like this:
foreach($array1 as $key=>$val){ // Loop though one array
$val2 = $array2[$key]; // Get the values from the other arrays
$val3 = $array3[$key];
$result[] = array( //Save result in third array
'id' => $val,
'quant' => $val2,
'name' => $val3,
);
}
This will only work if the both array have same count.I try in laravel, for inserting both array in mysql db
$answer = {"0":"0","1":"1","2":"0","3":"0","4":"1"};
$reason_id = {"0":"17","1":"19","2":"15","3":"19","4":"18"};
$k= (array)json_decode($answer);
$x =(array)json_decode($reason_id);
$number = COUNT(json_decode($reason_id, true));
if($number > 0)
{
for($i=0; $i<$number; $i++)
{
$val = new ModelName();
$val->reason_id = $x[$i];
$val->answer =$k[$i];
$val->save();
}
}
En laravel Livewire
return view('you_name_view', compact('data','data2'));
#foreach ($data as $index => $data )
<li>
<span>{{$data}}</span>
<span>{{$data2[$index]}}</span>
</li>
#endforeach
it works for me
$counter = 0;
foreach($codes as $code)
{
$codes_array[$counter]=$code;
$counter++;
}
$counter = 0;
foreach($names as $name)
{
echo $codes_array[$counter]."and".$name;
$counter++;
}

use 2 foreach loop in php simultaneously to retrieve the filenames from a directory [duplicate]

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?
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',
...
);
foreach operates on only one array at a time.
The way your array is structured, you can array_combine() them into an array of key-value pairs then foreach that single array:
foreach (array_combine($codes, $names) as $code => $name) {
echo '<option value="' . $code . '">' . $name . '</option>';
}
Or as seen in the other answers, you can hardcode an associative array instead.
Use array_combine() to fuse the arrays together and iterate over the result.
$countries = array_combine($codes, $names);
array_map seems good for this too
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
array_map(function ($code, $name) {
echo '<option value="' . $code . '">' . $name . '</option>';
}, $codes, $names);
Other benefits are:
If one array is shorter than the other, the callback receive null values to fill in the gap.
You can use more than 2 arrays to iterate through.
Use an associative array:
$code_names = array(
'tn' => 'Tunisia',
'us' => 'United States',
'fr' => 'France');
foreach($code_names as $code => $name) {
//...
}
I believe that using an associative array is the most sensible approach as opposed to using array_combine() because once you have an associative array, you can simply use array_keys() or array_values() to get exactly the same array you had before.
This worked for me:
$codes = array('tn', 'us', 'fr');
$names = array('Tunisia', 'United States', 'France');
foreach($codes as $key => $value) {
echo "Code is: " . $codes[$key] . " - " . "and Name: " . $names[$key] . "<br>";
}
Your code like this is incorrect as foreach only for single array:
<?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>';
}
?>
Alternative, Change to this:
<?php
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
$count = 0;
foreach($codes as $code) {
echo '<option value="' . $code . '">' . $names[count] . '</option>';
$count++;
}
?>
Why not just consolidate into a multi-dimensional associative array? Seems like you are going about this wrong:
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
becomes:
$dropdown = array('tn' => 'Tunisia', 'us' => 'United States', 'fr' => 'France');
You can use array_merge to combine two arrays and then iterate over them.
$array1 = array("foo" => "bar");
$array2 = array("hello" => "world");
$both_arrays = array_merge((array)$array1, (array)$array2);
print_r($both_arrays);
All fully tested
3 ways to create a dynamic dropdown from an array.
This will create a dropdown menu from an array and automatically assign its respective value.
Method #1 (Normal Array)
<?php
$names = array('tn'=>'Tunisia','us'=>'United States','fr'=>'France');
echo '<select name="countries">';
foreach($names AS $let=>$word){
echo '<option value="'.$let.'">'.$word.'</option>';
}
echo '</select>';
?>
Method #2 (Normal Array)
<select name="countries">
<?php
$countries = array('tn'=> "Tunisia", "us"=>'United States',"fr"=>'France');
foreach($countries as $select=>$country_name){
echo '<option value="' . $select . '">' . $country_name . '</option>';
}
?>
</select>
Method #3 (Associative Array)
<?php
$my_array = array(
'tn' => 'Tunisia',
'us' => 'United States',
'fr' => 'France'
);
echo '<select name="countries">';
echo '<option value="none">Select...</option>';
foreach ($my_array as $k => $v) {
echo '<option value="' . $k . '">' . $v . '</option>';
}
echo '</select>';
?>
Walk it out...
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
PHP 5.3+
array_walk($codes, function ($code,$key) use ($names) {
echo '<option value="' . $code . '">' . $names[$key] . '</option>';
});
Before PHP 5.3
array_walk($codes, function ($code,$key,$names){
echo '<option value="' . $code . '">' . $names[$key] . '</option>';
},$names);
or combine
array_walk(array_combine($codes,$names), function ($name,$code){
echo '<option value="' . $code . '">' . $name . '</option>';
})
in select
array_walk(array_combine($codes,$names), function ($name,$code){
#$opts = '<option value="' . $code . '">' . $name . '</option>';
})
echo "<select>$opts</select>";
demo
<?php
$codes = array ('tn','us','fr');
$names = array ('Tunisia','United States','France');
echo '<table>';
foreach(array_keys($codes) as $i) {
echo '<tr><td>';
echo ($i + 1);
echo '</td><td>';
echo $codes[$i];
echo '</td><td>';
echo $names[$i];
echo '</td></tr>';
}
echo '</table>';
?>
foreach only works with a single array. To step through multiple arrays, it's better to use the each() function in a while loop:
while(($code = each($codes)) && ($name = each($names))) {
echo '<option value="' . $code['value'] . '">' . $name['value'] . '</option>';
}
each() returns information about the current key and value of the array and increments the internal pointer by one, or returns false if it has reached the end of the array. This code would not be dependent upon the two arrays having identical keys or having the same sort of elements. The loop terminates when one of the two arrays is finished.
Instead of foreach loop, try this (only when your arrays have same length).
$number = COUNT($_POST["codes "]);//count how many arrays available
if($number > 0)
{
for($i=0; $i<$number; $i++)//loop thru each arrays
{
$codes =$_POST['codes'][$i];
$names =$_POST['names'][$i];
//ur code in here
}
}
array_combine() worked great for me while combining $_POST multiple values from multiple form inputs in an attempt to update products quantities in a shopping cart.
I think that you can do something like:
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
foreach ($codes as $key => $code) {
echo '<option value="' . $code . '">' . $names[$key] . '</option>';
}
It should also work for associative arrays.
I think the simplest way is just to use the for loop this way:
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
for($i = 0; $i < sizeof($codes); $i++){
echo '<option value="' . $codes[$i] . '">' . $names[$i] . '</option>';
}
if(isset($_POST['doors'])=== true){
$doors = $_POST['doors'];
}else{$doors = 0;}
if(isset($_POST['windows'])=== true){
$windows = $_POST['windows'];
}else{$windows = 0;}
foreach($doors as $a => $b){
Now you can use $a for each array....
$doors[$a]
$windows[$a]
....
}
I solved a problem like yours by this way:
foreach(array_keys($idarr) as $i) {
echo "Student ID: ".$idarr[$i]."<br />";
echo "Present: ".$presentarr[$i]."<br />";
echo "Reason: ".$reasonarr[$i]."<br />";
echo "Mark: ".$markarr[$i]."<br />";
}
You should try this for the putting 2 array in singlr foreach loop
Suppose i have 2 Array
1.$item_nm
2.$item_qty
`<?php $i=1; ?>
<table><tr><td>Sr.No</td> <td>item_nm</td> <td>item_qty</td> </tr>
#foreach (array_combine($item_nm, $item_qty) as $item_nm => $item_qty)
<tr>
<td> $i++ </td>
<td> $item_nm </td>
<td> $item_qty </td>
</tr></table>
#endforeach `
Few arrays can also be iterated like this:
foreach($array1 as $key=>$val){ // Loop though one array
$val2 = $array2[$key]; // Get the values from the other arrays
$val3 = $array3[$key];
$result[] = array( //Save result in third array
'id' => $val,
'quant' => $val2,
'name' => $val3,
);
}
This will only work if the both array have same count.I try in laravel, for inserting both array in mysql db
$answer = {"0":"0","1":"1","2":"0","3":"0","4":"1"};
$reason_id = {"0":"17","1":"19","2":"15","3":"19","4":"18"};
$k= (array)json_decode($answer);
$x =(array)json_decode($reason_id);
$number = COUNT(json_decode($reason_id, true));
if($number > 0)
{
for($i=0; $i<$number; $i++)
{
$val = new ModelName();
$val->reason_id = $x[$i];
$val->answer =$k[$i];
$val->save();
}
}
En laravel Livewire
return view('you_name_view', compact('data','data2'));
#foreach ($data as $index => $data )
<li>
<span>{{$data}}</span>
<span>{{$data2[$index]}}</span>
</li>
#endforeach
it works for me
$counter = 0;
foreach($codes as $code)
{
$codes_array[$counter]=$code;
$counter++;
}
$counter = 0;
foreach($names as $name)
{
echo $codes_array[$counter]."and".$name;
$counter++;
}

how to use two arrays in for each loop in php? [duplicate]

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?
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',
...
);
foreach operates on only one array at a time.
The way your array is structured, you can array_combine() them into an array of key-value pairs then foreach that single array:
foreach (array_combine($codes, $names) as $code => $name) {
echo '<option value="' . $code . '">' . $name . '</option>';
}
Or as seen in the other answers, you can hardcode an associative array instead.
Use array_combine() to fuse the arrays together and iterate over the result.
$countries = array_combine($codes, $names);
array_map seems good for this too
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
array_map(function ($code, $name) {
echo '<option value="' . $code . '">' . $name . '</option>';
}, $codes, $names);
Other benefits are:
If one array is shorter than the other, the callback receive null values to fill in the gap.
You can use more than 2 arrays to iterate through.
Use an associative array:
$code_names = array(
'tn' => 'Tunisia',
'us' => 'United States',
'fr' => 'France');
foreach($code_names as $code => $name) {
//...
}
I believe that using an associative array is the most sensible approach as opposed to using array_combine() because once you have an associative array, you can simply use array_keys() or array_values() to get exactly the same array you had before.
This worked for me:
$codes = array('tn', 'us', 'fr');
$names = array('Tunisia', 'United States', 'France');
foreach($codes as $key => $value) {
echo "Code is: " . $codes[$key] . " - " . "and Name: " . $names[$key] . "<br>";
}
Your code like this is incorrect as foreach only for single array:
<?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>';
}
?>
Alternative, Change to this:
<?php
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
$count = 0;
foreach($codes as $code) {
echo '<option value="' . $code . '">' . $names[count] . '</option>';
$count++;
}
?>
Why not just consolidate into a multi-dimensional associative array? Seems like you are going about this wrong:
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
becomes:
$dropdown = array('tn' => 'Tunisia', 'us' => 'United States', 'fr' => 'France');
You can use array_merge to combine two arrays and then iterate over them.
$array1 = array("foo" => "bar");
$array2 = array("hello" => "world");
$both_arrays = array_merge((array)$array1, (array)$array2);
print_r($both_arrays);
All fully tested
3 ways to create a dynamic dropdown from an array.
This will create a dropdown menu from an array and automatically assign its respective value.
Method #1 (Normal Array)
<?php
$names = array('tn'=>'Tunisia','us'=>'United States','fr'=>'France');
echo '<select name="countries">';
foreach($names AS $let=>$word){
echo '<option value="'.$let.'">'.$word.'</option>';
}
echo '</select>';
?>
Method #2 (Normal Array)
<select name="countries">
<?php
$countries = array('tn'=> "Tunisia", "us"=>'United States',"fr"=>'France');
foreach($countries as $select=>$country_name){
echo '<option value="' . $select . '">' . $country_name . '</option>';
}
?>
</select>
Method #3 (Associative Array)
<?php
$my_array = array(
'tn' => 'Tunisia',
'us' => 'United States',
'fr' => 'France'
);
echo '<select name="countries">';
echo '<option value="none">Select...</option>';
foreach ($my_array as $k => $v) {
echo '<option value="' . $k . '">' . $v . '</option>';
}
echo '</select>';
?>
Walk it out...
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
PHP 5.3+
array_walk($codes, function ($code,$key) use ($names) {
echo '<option value="' . $code . '">' . $names[$key] . '</option>';
});
Before PHP 5.3
array_walk($codes, function ($code,$key,$names){
echo '<option value="' . $code . '">' . $names[$key] . '</option>';
},$names);
or combine
array_walk(array_combine($codes,$names), function ($name,$code){
echo '<option value="' . $code . '">' . $name . '</option>';
})
in select
array_walk(array_combine($codes,$names), function ($name,$code){
#$opts = '<option value="' . $code . '">' . $name . '</option>';
})
echo "<select>$opts</select>";
demo
<?php
$codes = array ('tn','us','fr');
$names = array ('Tunisia','United States','France');
echo '<table>';
foreach(array_keys($codes) as $i) {
echo '<tr><td>';
echo ($i + 1);
echo '</td><td>';
echo $codes[$i];
echo '</td><td>';
echo $names[$i];
echo '</td></tr>';
}
echo '</table>';
?>
foreach only works with a single array. To step through multiple arrays, it's better to use the each() function in a while loop:
while(($code = each($codes)) && ($name = each($names))) {
echo '<option value="' . $code['value'] . '">' . $name['value'] . '</option>';
}
each() returns information about the current key and value of the array and increments the internal pointer by one, or returns false if it has reached the end of the array. This code would not be dependent upon the two arrays having identical keys or having the same sort of elements. The loop terminates when one of the two arrays is finished.
Instead of foreach loop, try this (only when your arrays have same length).
$number = COUNT($_POST["codes "]);//count how many arrays available
if($number > 0)
{
for($i=0; $i<$number; $i++)//loop thru each arrays
{
$codes =$_POST['codes'][$i];
$names =$_POST['names'][$i];
//ur code in here
}
}
array_combine() worked great for me while combining $_POST multiple values from multiple form inputs in an attempt to update products quantities in a shopping cart.
I think that you can do something like:
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
foreach ($codes as $key => $code) {
echo '<option value="' . $code . '">' . $names[$key] . '</option>';
}
It should also work for associative arrays.
I think the simplest way is just to use the for loop this way:
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
for($i = 0; $i < sizeof($codes); $i++){
echo '<option value="' . $codes[$i] . '">' . $names[$i] . '</option>';
}
if(isset($_POST['doors'])=== true){
$doors = $_POST['doors'];
}else{$doors = 0;}
if(isset($_POST['windows'])=== true){
$windows = $_POST['windows'];
}else{$windows = 0;}
foreach($doors as $a => $b){
Now you can use $a for each array....
$doors[$a]
$windows[$a]
....
}
I solved a problem like yours by this way:
foreach(array_keys($idarr) as $i) {
echo "Student ID: ".$idarr[$i]."<br />";
echo "Present: ".$presentarr[$i]."<br />";
echo "Reason: ".$reasonarr[$i]."<br />";
echo "Mark: ".$markarr[$i]."<br />";
}
You should try this for the putting 2 array in singlr foreach loop
Suppose i have 2 Array
1.$item_nm
2.$item_qty
`<?php $i=1; ?>
<table><tr><td>Sr.No</td> <td>item_nm</td> <td>item_qty</td> </tr>
#foreach (array_combine($item_nm, $item_qty) as $item_nm => $item_qty)
<tr>
<td> $i++ </td>
<td> $item_nm </td>
<td> $item_qty </td>
</tr></table>
#endforeach `
Few arrays can also be iterated like this:
foreach($array1 as $key=>$val){ // Loop though one array
$val2 = $array2[$key]; // Get the values from the other arrays
$val3 = $array3[$key];
$result[] = array( //Save result in third array
'id' => $val,
'quant' => $val2,
'name' => $val3,
);
}
This will only work if the both array have same count.I try in laravel, for inserting both array in mysql db
$answer = {"0":"0","1":"1","2":"0","3":"0","4":"1"};
$reason_id = {"0":"17","1":"19","2":"15","3":"19","4":"18"};
$k= (array)json_decode($answer);
$x =(array)json_decode($reason_id);
$number = COUNT(json_decode($reason_id, true));
if($number > 0)
{
for($i=0; $i<$number; $i++)
{
$val = new ModelName();
$val->reason_id = $x[$i];
$val->answer =$k[$i];
$val->save();
}
}
En laravel Livewire
return view('you_name_view', compact('data','data2'));
#foreach ($data as $index => $data )
<li>
<span>{{$data}}</span>
<span>{{$data2[$index]}}</span>
</li>
#endforeach
it works for me
$counter = 0;
foreach($codes as $code)
{
$codes_array[$counter]=$code;
$counter++;
}
$counter = 0;
foreach($names as $name)
{
echo $codes_array[$counter]."and".$name;
$counter++;
}

Increment an array counter

In the loop below I want $value[0] to increment on each pass of the loop. So, if $count = 2 the loop will run twice and output $key . " " . $value[0] and $key . " " . $value[1].
Right now, my loop is outputting $key . " " . $value[0] twice. What did I do wrong?
$count = count($updates['positionTitle']);
for($i = 1; $i<=$count; $i++){
foreach($updates as $key => $value){
if(!is_array($value))
echo $key . " " . $value . "<br/>";
else
echo $key . " " . $value[0]++ . "<br/>";
}
}
You need to store what the current index is. I'm not actually sure what loop you were talking about though. I'm assuming it was the outer for loop. I still think this is broken but based on your comment this is what you want.
$count = count($updates['positionTitle']);
$idx = 0;
for($i = 1; $i<=$count; $i++){
foreach($updates as $key => $value){
if(!is_array($value))
echo $key . " " . $value . "<br/>";
else
echo $key . " " . $value[$idx] . "<br/>";
}
$idx++;
}
Change:
foreach($updates as $key => $value){
To:
foreach($updates as $key => &$value){

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?
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',
...
);
foreach operates on only one array at a time.
The way your array is structured, you can array_combine() them into an array of key-value pairs then foreach that single array:
foreach (array_combine($codes, $names) as $code => $name) {
echo '<option value="' . $code . '">' . $name . '</option>';
}
Or as seen in the other answers, you can hardcode an associative array instead.
Use array_combine() to fuse the arrays together and iterate over the result.
$countries = array_combine($codes, $names);
array_map seems good for this too
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
array_map(function ($code, $name) {
echo '<option value="' . $code . '">' . $name . '</option>';
}, $codes, $names);
Other benefits are:
If one array is shorter than the other, the callback receive null values to fill in the gap.
You can use more than 2 arrays to iterate through.
Use an associative array:
$code_names = array(
'tn' => 'Tunisia',
'us' => 'United States',
'fr' => 'France');
foreach($code_names as $code => $name) {
//...
}
I believe that using an associative array is the most sensible approach as opposed to using array_combine() because once you have an associative array, you can simply use array_keys() or array_values() to get exactly the same array you had before.
This worked for me:
$codes = array('tn', 'us', 'fr');
$names = array('Tunisia', 'United States', 'France');
foreach($codes as $key => $value) {
echo "Code is: " . $codes[$key] . " - " . "and Name: " . $names[$key] . "<br>";
}
Your code like this is incorrect as foreach only for single array:
<?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>';
}
?>
Alternative, Change to this:
<?php
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
$count = 0;
foreach($codes as $code) {
echo '<option value="' . $code . '">' . $names[count] . '</option>';
$count++;
}
?>
Why not just consolidate into a multi-dimensional associative array? Seems like you are going about this wrong:
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
becomes:
$dropdown = array('tn' => 'Tunisia', 'us' => 'United States', 'fr' => 'France');
You can use array_merge to combine two arrays and then iterate over them.
$array1 = array("foo" => "bar");
$array2 = array("hello" => "world");
$both_arrays = array_merge((array)$array1, (array)$array2);
print_r($both_arrays);
All fully tested
3 ways to create a dynamic dropdown from an array.
This will create a dropdown menu from an array and automatically assign its respective value.
Method #1 (Normal Array)
<?php
$names = array('tn'=>'Tunisia','us'=>'United States','fr'=>'France');
echo '<select name="countries">';
foreach($names AS $let=>$word){
echo '<option value="'.$let.'">'.$word.'</option>';
}
echo '</select>';
?>
Method #2 (Normal Array)
<select name="countries">
<?php
$countries = array('tn'=> "Tunisia", "us"=>'United States',"fr"=>'France');
foreach($countries as $select=>$country_name){
echo '<option value="' . $select . '">' . $country_name . '</option>';
}
?>
</select>
Method #3 (Associative Array)
<?php
$my_array = array(
'tn' => 'Tunisia',
'us' => 'United States',
'fr' => 'France'
);
echo '<select name="countries">';
echo '<option value="none">Select...</option>';
foreach ($my_array as $k => $v) {
echo '<option value="' . $k . '">' . $v . '</option>';
}
echo '</select>';
?>
Walk it out...
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
PHP 5.3+
array_walk($codes, function ($code,$key) use ($names) {
echo '<option value="' . $code . '">' . $names[$key] . '</option>';
});
Before PHP 5.3
array_walk($codes, function ($code,$key,$names){
echo '<option value="' . $code . '">' . $names[$key] . '</option>';
},$names);
or combine
array_walk(array_combine($codes,$names), function ($name,$code){
echo '<option value="' . $code . '">' . $name . '</option>';
})
in select
array_walk(array_combine($codes,$names), function ($name,$code){
#$opts = '<option value="' . $code . '">' . $name . '</option>';
})
echo "<select>$opts</select>";
demo
<?php
$codes = array ('tn','us','fr');
$names = array ('Tunisia','United States','France');
echo '<table>';
foreach(array_keys($codes) as $i) {
echo '<tr><td>';
echo ($i + 1);
echo '</td><td>';
echo $codes[$i];
echo '</td><td>';
echo $names[$i];
echo '</td></tr>';
}
echo '</table>';
?>
foreach only works with a single array. To step through multiple arrays, it's better to use the each() function in a while loop:
while(($code = each($codes)) && ($name = each($names))) {
echo '<option value="' . $code['value'] . '">' . $name['value'] . '</option>';
}
each() returns information about the current key and value of the array and increments the internal pointer by one, or returns false if it has reached the end of the array. This code would not be dependent upon the two arrays having identical keys or having the same sort of elements. The loop terminates when one of the two arrays is finished.
Instead of foreach loop, try this (only when your arrays have same length).
$number = COUNT($_POST["codes "]);//count how many arrays available
if($number > 0)
{
for($i=0; $i<$number; $i++)//loop thru each arrays
{
$codes =$_POST['codes'][$i];
$names =$_POST['names'][$i];
//ur code in here
}
}
array_combine() worked great for me while combining $_POST multiple values from multiple form inputs in an attempt to update products quantities in a shopping cart.
I think that you can do something like:
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
foreach ($codes as $key => $code) {
echo '<option value="' . $code . '">' . $names[$key] . '</option>';
}
It should also work for associative arrays.
I think the simplest way is just to use the for loop this way:
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
for($i = 0; $i < sizeof($codes); $i++){
echo '<option value="' . $codes[$i] . '">' . $names[$i] . '</option>';
}
if(isset($_POST['doors'])=== true){
$doors = $_POST['doors'];
}else{$doors = 0;}
if(isset($_POST['windows'])=== true){
$windows = $_POST['windows'];
}else{$windows = 0;}
foreach($doors as $a => $b){
Now you can use $a for each array....
$doors[$a]
$windows[$a]
....
}
I solved a problem like yours by this way:
foreach(array_keys($idarr) as $i) {
echo "Student ID: ".$idarr[$i]."<br />";
echo "Present: ".$presentarr[$i]."<br />";
echo "Reason: ".$reasonarr[$i]."<br />";
echo "Mark: ".$markarr[$i]."<br />";
}
You should try this for the putting 2 array in singlr foreach loop
Suppose i have 2 Array
1.$item_nm
2.$item_qty
`<?php $i=1; ?>
<table><tr><td>Sr.No</td> <td>item_nm</td> <td>item_qty</td> </tr>
#foreach (array_combine($item_nm, $item_qty) as $item_nm => $item_qty)
<tr>
<td> $i++ </td>
<td> $item_nm </td>
<td> $item_qty </td>
</tr></table>
#endforeach `
Few arrays can also be iterated like this:
foreach($array1 as $key=>$val){ // Loop though one array
$val2 = $array2[$key]; // Get the values from the other arrays
$val3 = $array3[$key];
$result[] = array( //Save result in third array
'id' => $val,
'quant' => $val2,
'name' => $val3,
);
}
This will only work if the both array have same count.I try in laravel, for inserting both array in mysql db
$answer = {"0":"0","1":"1","2":"0","3":"0","4":"1"};
$reason_id = {"0":"17","1":"19","2":"15","3":"19","4":"18"};
$k= (array)json_decode($answer);
$x =(array)json_decode($reason_id);
$number = COUNT(json_decode($reason_id, true));
if($number > 0)
{
for($i=0; $i<$number; $i++)
{
$val = new ModelName();
$val->reason_id = $x[$i];
$val->answer =$k[$i];
$val->save();
}
}
En laravel Livewire
return view('you_name_view', compact('data','data2'));
#foreach ($data as $index => $data )
<li>
<span>{{$data}}</span>
<span>{{$data2[$index]}}</span>
</li>
#endforeach
it works for me
$counter = 0;
foreach($codes as $code)
{
$codes_array[$counter]=$code;
$counter++;
}
$counter = 0;
foreach($names as $name)
{
echo $codes_array[$counter]."and".$name;
$counter++;
}

Categories