Nested foreach loop, break inside loop - php

I try to create a list with nested foreach loop. First loop is looping some numbers, second loop is looping dates. I want to write one number to one date. So there is a another function to check that. But the result is numbers writes on dates multiple times.
Out is something like that :
number 5 is on 2013.01.15;
number 5 is on 2013.01.16;
number 5 is on 2013.01.17;
number 6 is on 2013.01.15;
number 6 is on 2013.01.17;
The code :
function create_event($numbers,$available_dates) {
foreach($numbers as $number) {
foreach($avaliable_dates as $av_date) {
$date_check= dateCheck($av_date,$number);
if ($date_check == 0) {
echo "number ".$number." is on ".$av_date;
break;
} else {
$send_again[] = $number;
}
}
}
create_event($send_again,$avaliable_dates);
}
I think inside loop is not break.

Your break; should break inner foreach loop!
The only reason for such behavior I see is repeating numbers in you array!(E.g. $numers=array(5,5,5,6,6); )
Try to insert: $numbers=array_unique($numbers); before your outer foreach loop
If you need to break both loops(inner and outer) write break 2; instead of break;

Can you check something like this:
function create_event($numbers,$available_dates) {
foreach ($numbers as $number) {
foreach ($available_dates as &$av_date) {
if (dateCheck($av_date, $number) == 0) {
unset($av_date);
break;
}
}
}
}

Related

best way to loop calculations in php

i want to calculate two operations with the help of loop. They are already working and providing result i need. But i want them to look more like coding. So if anybody can help them with the help of for in php
for($i=0;i<something;$i++){
$temp_calc = ;
}
here are two statements.
In first statement length of array is 9.
In second statement length of array is 12.
both statements to be solved in different for loop as they are totally different questions.
$temp_calc = 10*$temp_array[0]+9*$temp_array[1]+8*$temp_array[2]+7*$temp_array[3]+6*$temp_array[4]+5*$temp_array[5]+4*$temp_array[6]+3*$temp_array[7]+2*$temp_array[8];
$temp_calc = 1*$temp_array[0]+3*$temp_array[1]+1*$temp_array[2]+3*$temp_array[3]+1*$temp_array[4]+3*$temp_array[5]+1*$temp_array[6]+3*$temp_array[7]+1*$temp_array[8]+3*$temp_array[9]+1*$temp_array[10]+3*$temp_array[11];
Thanks in advance
It will be a little simpler to use a foreach loop rather than a for loop. If you specifically need to use a for loop because it is a requirement of an assignment, you can check the PHP documentation. There are some examples there of using a for loop to loop over an array. This is a common and basic control structure and it will be more valuable for you to really understand how to use it. The more important part is what goes on inside the loop. There are multiple ways to do this, but here are some basic examples.
First one:
// initialize multiplier and result outside the loop
$multiplier = 10;
$result = 0;
// loop over the values
foreach ($temp_array as $value) {
// add the value * multiplier to the result and decrement the multiplier
$result += $value * $multiplier--;
}
Second one
// initialize multiplier and result outside the loop
$multiplier = 1;
$result = 0;
// loop over the values
foreach ($temp_array as $value) {
// add the value * multiplier to the result
$result += $value * $multiplier;
// switch the multiplier to the alternating value
if ($multiplier == 1) {
$multiplier = 3;
} else {
$multiplier = 1;
}
// The switch can be done more simply using a ternary operator like this:
// $multiplier = $multiplier == 1 ? 3 : 1;
}
for both issues:
$temp_array = array(2,2,2,2,2,2,2,2,2);//sample
function calc_1($temp_array){//first
$total=0;
$count = count($temp_array)+1;
foreach($temp_array as $value){
$total += $count*$value;
$count-=1;
}
return $total;
}
function calc_2($temp_array){//second
$total=0;
foreach($temp_array as $k=>$value){
$total += ($k%2==0) ? 1*$value : 3*$value;//when is even or odd
}
return $total;
}
var_dump(calc_1($temp_array));//resp1
var_dump(calc_2($temp_array));//resp2
If your array is called $myArray, then:
/*Since I can't know what the sequence of the values are that you
are multiplying, and because you might need other sequences in the
future, a function was developed that chooses which sequence you
want to multiply.*/
function findSomeValues($arraySize)
{
switch ($arraySize) {
case 9:
{
$someValues = array(10,9,8,7,4,5,4,3,2);
}
break;
case 12:
{
$someValues = array(1,3,1,3,1,3,1,3,1,3,1,3);
}
break;
default:
$someValues = array();
}
return $someValues;
}
/*This following function then finds how big your array is, looks
for a sequence stored in the findSomeValues function. If a sequence
exist for that array size (in this case if you have an array either
9 or 12 elements long), the result will be calculated and echoed. If
the sequence was not found, an error message would be echoed.*/
function multiplyValues($myArray) {
$result = 0;
$arraySize = count($myArray);//obtaining array size
$someValues = findSomeValues($arraySize);//obtaining sequence to multiply with
if (count($someValues)>0)
{
for($i=0;i<$arraySize;$i++){
$result += $myArray[i]*$someValues[i];
}
echo "result = ".$result."<br>";//result message
}
else
{
echo "you are missing some values<br>";//error message
}
}
Let me know if that worked for you.
Alternative:
If you prefer something a bit simpler:
//this array holds the sequences you have saved:
$sequenceArray = array(
9 => array(10,9,8,7,4,5,4,3,2),
12 => array(1,3,1,3,1,3,1,3,1,3,1,3)
);
//this function does the multiplication:
function multiplyValues($myArray)
{
$arraySize = count($myArray);
for($i=0;i<$arraySize;$i++){
$result += $myArray[i]*$sequenceArray[i];
}
echo "result = ".$result."<br>";//result message
}
For your result
$temp_calc = 10*$temp_array[0]+9*$temp_array[1]+8*$temp_array[2]+7*$temp_array[3]+6*$temp_array[4]+5*$temp_array[5]+4*$temp_array[6]+3*$temp_array[7]+2*$temp_array[8];
You should have for loop as following. It will run the loop till 8th index of your temp_array and multiply each index value with $i and sum up in a variable $temp_calc_1.
<?php
$temp_calc_1 = 0;
for($i=0;$i<9;$i++){
$temp_calc_1 = $temp_calc_1 + ( 10-$i)*$temp_array[$i] ;
}
For your second result
$temp_calc = 1*$temp_array[0]+3*$temp_array[1]+1*$temp_array[2]+3*$temp_array[3]+1*$temp_array[4]+3*$temp_array[5]+1*$temp_array[6]+3*$temp_array[7]+1*$temp_array[8]+3*$temp_array[9]+1*$temp_array[10]+3*$temp_array[11];
The above should be converted to the following loop, this will run loop till your 12th index of temparrayand do the calculation. This time it will multiply each index value of temparray by either 1 and 3. So first time it will multiply with 1 and next time with 3 and so on
//
$temp_calc_2 = 0;
for($i=0;$i<12;$i++){
$j = $i%2?3:1;
$temp_calc_2 = $temp_calc_2 + $j*$temp_array[$i] ;
}
?>

Know the count of for-each loop before executing that loop

How may i know that - In php how many times the foreach loop will get run, before that loop get executed..In other words i want to know the count of that particular loop. I want to apply some different css depends upon the count.
Use the function count to get the amount of numbers in your array.
Example:
$array = array('test1', 'test2');
echo count($array); // Echos '2'
Or if you want to be an engineer for-sorts you can set up something like so:
$array = array('test1', 'test2');
$count = 0;
foreach ($array as $a) { $count++; }
And that can count it for you, and the $count variable will hold the count, hope this helped you.
Simply count() the array and use the output as a condition, like:
if (count($array) > 100) {
// This is an array with more than 100 items, go for plan A
$class = 'large';
} else {
// This is an array with less than 100 items, go for plan B
$class = 'small';
}
foreach ($array as $key => $value) {
echo sprintf('<div id="%s" class="%s">%s</div>', $key, $class, $value);
}

Repeat ForEach Loop (PHP) But Break [duplicate]

I have a php array $numbers = array(1,2,3,4,5,6,7,8,9)
if I am looping over it using a foreach foreach($numbers as $number)
and have an if statement if($number == 4)
what would the line of code be after that that would skip anything after that line and start the loop at 5? break, return, exit?
You are looking for the continue statement. Also useful is break which will exit the loop completely. Both statements work with all variations of loop, ie. for, foreach and while.
$numbers = array( 1, 2, 3, 4, 5, 6, 7, 8, 9 );
foreach( $numbers as $number ) {
if ( $number == 4 ) { continue; }
// ... snip
}
continue;
Continue will tell it to skip the current iteration block, but continue on with the rest of the loop. Works in all scenerios (for, while, etc.)
Break; will stop the loop and make compiler out side the loop. while continue; will just skip current one and go to next cycle.
like:
$i = 0;
while ($i++)
{
if ($i == 3)
{
continue;
}
if ($i == 5)
{
break;
}
echo $i . "\n";
}
Output:
1
2
4
6 <- this won't happen
I suppose you are looking for continue statement. Have a look at http://php.net/manual/en/control-structures.continue.php
dinel

Limit a multidimensional array response

Having 3 multidimensional arrays, to whom I do a foreach how can I limit the multidimensional response inside foreach from X items to lets say 20.
Code:
$i = 0;
foreach ($value->channel->item as $item)
{
$data['data'][$keySection]['item1'][$i]['url'] = $item->url;
$data['data'][$keySection]['item1'][$i]['title'] = $item->title;
$data['data'][$keySection]['item1'][$i]['img'] = $item->thumb;
$i++;
}
where $value is contained within
foreach ($homeData as $keySection => $valueSection)
{
foreach($valueSection as $key => $value)
{
switch ($key)
{
I've tried aplying some fors both within foreach ($value->channel->item as $item) as outside but I just can't get it to work properly, I get either doubled results or not working at all.
How can I make this work??
Edit:
$i has nothing to do with it... I need to limit $value->channel->item where item contains X results
Edit2:
$i is for $homeData where $homeData contains three values and each and one of those will later contain 3 different values of $value->channel->item so if item contains 20 results, will be 3x20 = 60 and $i is ment to separate each 20 results...
Edit3:
ok, now I get it... sorry for the misunderstanding
After you start the foreach, add:
if($i > 19) {
break;
}
This checks if $i is greater than 19 (which means 20 iterations) and then breaks this foreach loop. More information about break, here.
You can do it like :
$i = 0;
foreach ($value->channel->item as $item)
{
if($i > 19) {
break;
}
$data['data'][$keySection]['item1'][$i]['url'] = $item->url;
$data['data'][$keySection]['item1'][$i]['title'] = $item->title;
$data['data'][$keySection]['item1'][$i]['img'] = $item->thumb;
$i++;
}
This will give you 20 items.
Hope this is what you want :)

PHP, continue; on foreach(){ foreach(){

Is there a way to continue on external foreach in case that the internal foreach meet some statement ?
In example
foreach($c as $v)
{
foreach($v as $j)
{
if($j = 1)
{
continue; // But not the internal foreach. the external;
}
}
}
Try this, should work:
continue 2;
From the PHP Manual:
Continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of.
here in the examples (2nd exactly) described code you need
Try this: continue 2; According to manual:
continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of.
There are two solutions available for this situation, either use break or continue 2. Note that when using break to break out of the internal loop any code after the inner loop will still be executed.
foreach($c as $v)
{
foreach($v as $j)
{
if($j = 1)
{
break;
}
}
echo "This line will be printed";
}
The other solution is to use continue followed with how many levels back to continue from.
foreach($c as $v)
{
foreach($v as $j)
{
if($j = 1)
{
continue 2;
}
}
// This code will not be reached.
}
This will continue to levels above (so the outer foreach)
continue 2
<?php
foreach($c as $v)
{
foreach($v as $j)
{
if($j = 1)
{
continue 2; // note the number 2
}
}
}
?>
RTM
Try break instead of continue.
You can follow break with an integer, giving the number of loops to break out of.
you have to use break instead of continue, if I get you right
Here I wrote an explanation on the matter: What is meant by a number after "break" or "continue" in PHP?

Categories