two foreach loop on if statement - php

Wondering if it's possible to have a foreach loop call on if statement like this :
if (class_exists('WooCommerce')) {
foreach (array_combine($val1, $val2) as $key => $row_values)
}
else {
foreach ( $val1 as $key => $row_values )
}
{ begin of loop code
What I'm trying to do is to have a foreach loop if woocommerce plugin is active and to have another foreach loop if woocommerce isn't active.

This is not possible the way you try it, since that is invalid syntax.
What you can do is something like that:
<?php
$iterationArray = class_exists('WooCommerce') ? array_combine($val1, $val2) : $val1;
foreach ($iterationArray as $key => $row_values) {
// begin of loop code
} // end loop

What you need to do if a condition before the loop to assign the variables you will use to loop, just like this:
if ( class_exists( 'WooCommerce' ) ) {
$newVal = array_combine($val1, $val2);
} else {
$newVal = $val1;
}
foreach ( $newVal as $key => $row_values ) {
// do stuff
}
The result will be the same as what you were trying to do. But the syntax you proposed in your question is not supported in PHP, and can be worked around with the way proposed above.

Related

Modify array during multiple foreach loop iterations

I've to update data for array which has 4 foreach loops,
foreach ($dta['hotels']['hotels'] as $key => &$value) {
foreach ($value['rooms'] as $key1 => $value1) {
foreach ($value1['rates'] as $key2 => $value2) {
foreach ($value2['shiftRates'] as $key3 => &$value3) {
$value3['net'] = 0.000072*$value3['net'];
$value3['sellingRate'] = 0.000072*$value3['sellingRate'];
var_dump($value3['sellingRate']);
}
}
}
$value['currency'] = 'USD';
}
I want to update data of very deep 4th foreach loop, which isn't updating data, where as first loop data update was possible.
i've tried to put "&" but in first loop it worked and in 4th loop it's not working.
Any possible solutions ?
You have all keys, you can use these to modify your values :
$dta['hotels']['hotels'][$key]['rooms'][$key1]['rates'][$key2]['shiftRates'][$key3]['sellingRate'] = 0.000072 * $value3['sellingRate'];
As long as there are no other net or sellingRate keys somewhere else in the array that you don't want to modify, you can do this more simply with array_walk_recursive.
array_walk_recursive($dta, function(&$value, $key) {
if ($key === 'net' || $key === 'sellingRate') {
$value *= 0.000072;
}
});

Array key as variable in foreach - PHP

This is probably very simple ... but I can't figure it out. I need to use array keys as variables. I have three tabs that need to use unique variables to access data.
$array = array(
'items' => 'latest',
'itemsFollow' => 'follow',
'itemsExp' => 'expired'
);
while ( ($stuff = current($array)) !== FALSE ) {
echo '<div id="'.key($array).'" class="tab-content grid flex">';
foreach(/*array_key*/ as $item) { //need foreach($items, foreach($itemsFollow and foreach($itemsExp
// do stuff
}
echo '</div>';
next($array);
}
Loop through your array with foreach. There is no need to loop twice (nested loops) in a one dimensional array. Use if, elseif or case statements to do custom stuff depending on the value.
foreach ($array as $key => $value){
echo '<div id="'.$key.'" class="tab-content grid flex">';
if($value=="latest"){
//do stuff
}
elseif($value=="follow"){
//do stuff
}
elseif($value=="expired"){
//do stuff
}
}

Dynamic add to current foreach array

I have a loop that needs to go through each item. So naturally a foreach loop seems like the best idea. However, I need to add an element to the array as it iterates. I tried the following without any luck.
foreach ($allitems as $item) {
//Do some stuff here
if ($value === true)
$allitems[] = 'New item';
}
I found out the foreach loops seem to use a referenced copy of the array, so editing the array does not register in the loop.
A workaround is to use the older styled while loops as follows:
while (list($key, $item) = each($allitems)) {
//Do some stuff here
if ($value === true)
$allitems[] = 'New item';
}
Clearly a foreach loop would be nicer and more efficient. Is it possible? Or is the while structure the best possible solution.
Yeah, it is possible:
foreach ($allitems as &$item) {
//Do some stuff here
if ($value === true)
$allitems[] = 'New item';
}
According to the docs, you need to pass a reference (using the & in front if $item)
More concrete example:
<?php
$allitems = array(1,2,3,4);
foreach ($allitems as &$item) {
echo $item."\n";
if ($item == 2) {
$allitems[] = "Blah";
}
}
?>
This outputs (using php from commandline)
1
2
3
4
Blah
It seems like an ordinary for loop would be best for this:
for ($i = 0; $i < count($array); $i++) {
// Do some stuff here that calculates $value from $array[$i]
if ($value === true) {
$array[] = "New Element";
}
}
You could do foreach...like this....
But it adds more code...so its not any better than your while loop..
foreach($array as $val){
if($val=="check"){$append[]="New Item";}
}
$array = array_merge($array, $append);
Of course, if you want your structure maintained..then rather use array_push

Anything to attend when changing values in a multidimensional foreach() loop?

I got a site that executes the following code
$keywords = ($_SESSION[$_POST['ts']]);
print_r($keywords);
foreach ($keywords as $keyword) {
foreach ($keyword['whitelist'] as $entry) {
foreach ($_POST as $key => $value) {
if ($key == $entry['encoded_url']) {
$entry['ignore'] = $value;
$decodedURL = $this->base64->url_decode($entry['encoded_url']);
if ($value == 'noignore') {
echo "found!<br />";
$this->blacklist_model->remove($decodedURL);
$html = $this->analyse->getHTML($decodedURL);
$entry['html'] = $html[0];
$entry['loading_time'] = $html[1];
}
if($value == 'alwaysignore') {
$this->blacklist_model->add($decodedURL);
}
}
}
}
}
print_r($keywords);
The output looks like this:
http://pastebin.com/B3PtrqjB
So, as you see, there are several "found!"s in the output, so the if clause actually gets executed a few times and I expected the second array to contain new data like 'html', but, as you see, nothing changes. Is there anything to attend when changing values in multidimensional foreach() loops?
foreach creates a copy of the array and loops through that. Modifying values doesn't work.
You can get around this, though, by using references.
foreach ($keywords as &$keyword) {
foreach ($keyword['whitelist'] as &$entry) {
foreach ($_POST as $key => &$value) {
...
}
}
}
With that you can modify $value and it WILL affect the original array.
You suppose to change the Original array.
$entry is just an instance / unconnected node.
you need to change $keywords, and not its on the fly created nodes.

foreach code in PHP

I would like to iterate through an xml document to get its values. See the given code
foreach ($xml->children() as $key1=>$value1 /*($xml->children() as $second_gen)*/ ) {
echo ' 1 ' .$key1.' '.$value1.'<br>';
foreach ($second_gen as $key2=>$value2) {
echo ' ___2 ' .$key2.' '.$value2.'<br>';
}
}
So what I want to do is to make $second_gen equals to the children of the each current iteration of the loop. I was able to do this by putting it in the foreach, but this prevented me from using key/value. So is there any solution to get both?
Thanks!
The value in a foreach loop equals to the value itself. So if you leave out the $key => part or not doesn't change the $value:
foreach ( $xml->children() as $key1 => $value1 )
{
foreach ( $value1->children() as $key2 = $value2 )
{
// ...
}
}

Categories