Multiple index variables in PHP foreach loop
to achieve just that result you could do
foreach (array_combine($courses, $sections) as $course => $section)
but that only works for two arrays
php: foreach() how to assign to two variables
It does not work the way you outline with your pseudo code. However, the SPL offers a way to iterate multiple iterators at once. It's called MultipleIterator
and you can attach as many iterators as you like:
$multi = new MultipleIterator();
$multi->attachIterator(new ArrayIterator($array1));
$multi->attachIterator(new ArrayIterator($array2));
foreach($multi as $value)
{
list($key1, $key2) = $multi->key();
list($value1, $value2) = $value;
}
See it in action: Demo
Edit: The first example shows a suggestion from the SPL. It has the benefit that it can deal with any kind of iterators, not only arrays. If you want to express something similar with arrays, you can achieve something similar with the classic while(list()=each())
loop, which allows more expressions than foreach
.
while
(
(list($key1, $value1) = each($array1))
&& (list($key2, $value2) = each($array2))
)
{
printf("%s => %s, %s => %s \n", $key1, $value1, $key2, $value2);
}
Demo (the minimum number of elements are iterated)
See as well a related question: Multiple index variables in PHP foreach loop
Foreach multiple variables
Maybe this will do the trick.
function get_order_item_lines($skus = '', $qty = '')
{
$xml = '';
if (!empty($skus) && is_array($skus))
{
foreach ($skus as $key => $sku)
{
$skuUpper = strtoupper($sku); // change to upper
if ($skuUpper != 'WANHAO-STICKER'
&& strpos($skuUpper, 'NWS-', 0) === false) // string not contains..
{
$xml .= "<L>".PHP_EOL;
$xml .= "<P>" . $sku . "</P>".PHP_EOL;
$xml .= "<Q>" . (empty($qty[$key]) ? "" : $qty[$key]) . "</Q>".PHP_EOL;
$xml .= "</L>".PHP_EOL;
}
}
}
else
{
$skus = explode( ",", $skus );
if ( !empty( $skus[0] ) && !empty( $qty[0] ) )
{
$skuUpper = strtoupper($skus[0]); // change to upper
if ($skuUpper != 'WANHAO-STICKER'
&& strpos($skuUpper, 'NWS-', 0) === false)
{
$xml .= "<L>".PHP_EOL;
$xml .= "<P>" . trim( $skus[0] ) . "</P>".PHP_EOL;
$xml .= "<Q>" . (empty($qty[0]) ? "" : $qty[0]) . "</Q>".PHP_EOL;
$xml .= "</L>".PHP_EOL;
}
}
}
return $xml;
}
How to pass multiple variables in foreach php
Main problem is that $short_smas
and $mid_smas
have different size. Moreover they are associative arrays so either you pick unique keys from both and will allow for empty values for keys that have only one value available or you pick only keys present in both arrays. Code below provides first solution.
// first lets pick unique keys from both arrays
$uniqe_keys = array_unique(array_merge(array_keys($short_smas), array_keys($mid_smas)));
// alternatively we can only pick those present in both
// $intersect_keys = array_intersect(array_keys($short_smas),array_keys($mid_smas));
// now lets build sql in loop as Marcelo Agimóvel sugested
// firs we need base command:
$sql = "INSERT INTO sma (short_sma, mid_sma) VALUES ";
// now we add value pairs to coma separated list of values to
// insert using keys from prepared keys array
foreach ($uniqe_keys as $key) {
$mid_sma = array_key_exists($key, $mid_smas)?$mid_smas[$key]:"";
$short_sma = array_key_exists($key, $short_smas)?$short_smas[$key]:"";
// here we build coma separated list of value pairs to insert
$sql .= "('$short_sma', '$mid_sma'),";
}
$sql = rtrim($sql, ",");
// with data provided in question $sql should have string:
// INSERT INTO sma (short_sma, mid_sma) VALUES, ('3.5', ''), ('4.5', ''), ('5.5', ''), ('6.5', '5'), ('7.5', '6'), ('8.5', '7'), ('9.5', '8'), ('10.5', '9'), ('11.5', '10'), ('12.5', '11')
// now we execute just one sql command
if ($con->query($sql) === TRUE) {
echo "New records created successfully<br><br>";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
// don't forget to close connection
Marcelo Agimóvel also suggested that instead of multiple inserts like this:
INSERT INTO tbl_name (a,b,c) VALUES (1,2,3);
its better to use single:
INSERT INTO tbl_name
(a,b,c)
VALUES
(1,2,3),
(4,5,6),
(7,8,9);
That's why I append value pairs to $sql
in foreach
loop and execute query outside loop.
Also its worth mentioning that instead of executing straight sql its better to use prepared statements as they are less prone to sql injection.
How to pass multiple values with a common index key in a foreach loop?
<?php
foreach (array_keys($_POST['column1']) as $key) {
$value = $_POST['column1'][$key];
$value1 = $_POST['column2'][$key];
$stmt = $mysqli->prepare("UPDATE table SET column1 = ?, column2 = ? WHERE id = ?");
$stmt->bind_param('ssi',$value,$value1,$key);
$stmt->execute();
}
Two arrays in foreach loop
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',
...
);
PHP foreach loop with multiple index variables
This way is not really good at all. The textfields will be posted not matter if they're empty or has content, while the checkboxes only is posted when checked. This will cause the arrays to be of different length and array_combine will fail.
Do a print_r($_POST) and you'll see what input is posted.
And that's not even considering the security nightmare this will create.
Calculations multiple arrays in foreach loop?
As CBroe stated in the comments, you can just use the key/index in the foreach loop to create the sum
<?php
$data = [
[
'indexname0' => 'group-id',
'indexname1' => 'name of 1st-item',
'indexname2' => 'state of 1st-item',
'indexname3' => 93.42,
'indexname4' => 'unit of 1st-item',
],
[
'indexname0' => 'group-id',
'indexname1' => 'name of 1st-item',
'indexname2' => 'state of 1st-item',
'indexname3' => 93.12,
'indexname4' => 'unit of 1st-item',
],
[
'indexname0' => 'group-id',
'indexname1' => 'name of 1st-item',
'indexname2' => 'state of 1st-item',
'indexname3' => 89.92,
'indexname4' => 'unit of 1st-item',
],
[
'indexname0' => 'group-id',
'indexname1' => 'name of 1st-item',
'indexname2' => 'state of 1st-item',
'indexname3' => 89.70,
'indexname4' => 'unit of 1st-item',
],
];
foreach($data as $index => $value) {
if (!isset($data[$index+1])) continue;
echo $data[$index+1]['indexname3'] - $data[$index]['indexname3'].'<br />';
}
demo
PHP - Use multiple values in foreach loop
php > $a = [1, 2, 3];
php > $b = [4, 5, 6];
php > $c = array_map(function($x, $y){ return $x + $y; }, $a, $b);
php > print_r($c);
Array
(
[0] => 5
[1] => 7
[2] => 9
)
php > print_r(implode($c, '|') . '|');
5|7|9|
Related Topics
Getting Last Month's Date in PHP
How to Get the Subversion Revision Number in PHP
Deleting a File After User Download It
Setting Up Laravel on a MAC PHP Artisan Migrate Error: No Such File or Directory
How to Compress/Decompress a Long Query String in PHP
Prevent Direct Url Access to PHP File
New Csrf Token Per Request or Not
Symfony 2 Entitymanager Injection in Service
How to Solve Time Out in PHPmyadmin
Using the PHP Http_Accept_Language Server Variable
Best Practice: Import MySQL File in PHP; Split Queries
Include Files from Parent or Other Directory
How to Get Greenwich Mean Time in PHP