PHP for loop - how to escape first iteration? - php

Given this PHP for loop
$row->frequency = 1;
$row->date_1 = 10000;
$row->interval = 86400;
for ($i = 0; $i <= $row->frequency; $i++) {
$cal_data[] = array(
'start' => strtotime($row->date_1) + $row->interval,
);
}
I would like the first iteration of the loop to ignore the + $row->interval giving me as a result:
10000
96400
I've seen this done with modulus but couldn't manage to make it work here. Anyone have suggestions?
Thanks!

Use + ($i ? $row->interval : 0)
In other words, if $i is zero - first iteration - add 0 instead of $row->interval. This is the ternary operator, (condition ? iftrue : iffalse) which is roughly equivalent to an if/else construction except it can be used amidst a statement.

for ($i = 0; $i <= $row->frequency; $i++) {
if ($i == 0) {
$val = strtotime($row->date_1) ;
} else {
$val = strtotime($row->date_1) + $row->interval;
}
$cal_data[] = array(
'start' => $val
);
}

Related

I am trying to get number of occurrences of a charaters in a string

Below is the code i tried, where count is showing improper.
Please help me to get where i am missing the logic.
I am attaching the code which i have tried so far.
PS Note:- I am not intended to use more built in function of php and so I created function for string length.
error_reporting(E_ALL);
$string = "ssddk";
function checkString($addinString, &$stringBK) {
if (empty(count($stringBK))) {
$stringBK[] = $addinString;
return false;
}
foreach ($stringBK as $key => $val) {
if ($addinString == $val) {
return true;
}
}
$stringBK[] = $addinString;
return false;
}
for ($i = 0; $i < checkstrlength($string); $i++) {
$count = 0;
for ($j = 0; $j < checkstrlength($string); $j++) {
if ($string[$i] == $string[$j]) {
if (checkString($string[$i], $stringBK)) {
continue 2;
}
$count++;
echo "Column => " . $string[$j] . " for count" .$count . "<br>";
}
}
}
function checkstrlength($string) {
$count = 0;
for ($i = 0; $string[$i] != ""; $i++) {
$count++;
}
return $count;
}
It gives below output ,
Column => s for count1
Column => d for count1
Column => k for count1
I am expecting it as ,
Column => s for count 2
Column => d for count 2
Column => k for count 1
Ok, there a couple of things to look at here.
The checkstrlength() has the below loop.
for ($i = 0; $string[$i] != ""; $i++) {
Formally speaking, we usually look at \0 terminating character in the string to terminate our loop. But in PHP, everything is a string. So, \0 is now a string to match on rather than a character match. Better, we do an isset check to stop our loop. So, code would look like:
for ($i = 0; isset($string[$i]); $i++) {
Second is your not caching the result which you got from checkstrlength(). Do it. Also, you can start the inner loop from $i itself. There is no need to go from start again. So, for loop would look like:
$length = checkstrlength($string);
for ($i = 0; $i < $length; $i++) {
for ($j = $i; $j < $length; $j++) {
Third is that there is no need of empty and count checks in checkString. This also reduces inbuilt function calls. You can simply loop over and return true if found. If not found, we are adding it anyway. So it would look like:
function checkString($addinString, &$stringBK) {
foreach ($stringBK as $key => $val) {
if ($addinString == $val) {
return true;
}
}
$stringBK[] = $addinString;
return false;
}
Now, in your nested loop, you add it to $stringBK outside of the inner loop, because there is no point in checking with the inner loop when chars match. This is because if some character was visited, why initialize the inner loop at all. Just have a check above and continue the search and count. Also note that you are having echo statements inside the inner loop which doesn't make sense because we haven't finished the count yet. Let's do and print it outside of the inner loop at the end. Snippet as follows:
for ($i = 0; $i < $length; $i++) {
$count = 0;
if (checkString($string[$i], $stringBK)) {
continue;
}
for ($j = $i; $j < $length; $j++) {
if ($string[$i] == $string[$j]) {
$count++;
}
}
echo "Column => " . $string[$i] . " for count : " .$count,PHP_EOL;
}
Final Code Demo: https://3v4l.org/4dpST

Multiple comparisons inside for loops don't break php code. Why?

Why this piece of code works when it is clearly wrong in the second for loop (for ($i==0; $i<$parts; $i++) {)?
Does php allows for multiple comparisons inside for loops?
function split_integer ($num,$parts) {
$value = 0;
$i = 0;
$result = [];
$modulus = $num%$parts;
if ($modulus == 0) {
for($i = 0; $i < $parts; $i++)
{
$value = $num/$parts;
$result[] = $value;
}
} else {
$valueMod = $parts - ($num % $parts);
$value = $num/$parts;
for ($i==0; $i<$parts; $i++) {
if ($i >= $valueMod) {
$result[] = floor($value+1);
} else {
$result[] = floor($value);
}
}
}
return $result;
}
Code for ($i==0; $i < $parts; $i++) runs because $i==0 has no impact on loop.
In normal for loop first statement just sets $i or any other counter's initial value. As you already set $i to 0 earlier, your loop runs from $i = 0 until second statement $i < $parts is not true.
Going further, you can even omit first statement:
$i = 0;
for (; $i < 3; $i++) {
echo $i;
}
And loop will still run 3 times from 0 to 2.

PHP for loop within for loop with different incrementing values

I am new to PHP and for loops but I am having trouble racking my brain around the math for this. I am trying to write a loop that will create an array with 49 items. The items have two incrementing values within them. The 49 items are below:
M1s1t1url
M1s1t2url
M1s1t3url
M1s1t4url
M1s1t5url
M1s1t6url
M1s1t7url
M1s2t1url
M1s2t2url
M1s2t3url
M1s2t4url
M1s2t5url
M1s2t6url
M1s2t7url
M1s3t1url
M1s3t2url
M1s3t3url
M1s3t4url
M1s3t5url
M1s3t6url
M1s3t7url
M1s4t1url
M1s4t2url
M1s4t3url
M1s4t4url
M1s4t5url
M1s4t6url
M1s4t7url
M1s5t1url
M1s5t2url
M1s5t3url
M1s5t4url
M1s5t5url
M1s5t6url
M1s5t7url
M1s6t1url
M1s6t2url
M1s6t3url
M1s6t4url
M1s6t5url
M1s6t6url
M1s6t7url
M1s7t1url
M1s7t2url
M1s7t3url
M1s7t4url
M1s7t5url
M1s7t6url
M1s7t7url
As you can see there are three numbers in each item. The first number is a constant. The second number counts up to 7 then resets back to 1. The third number adds 1 every time the second number resets back to 1. Here is what I have below but I know I am off on the calculations.
for ($i = 1; $i < 8; $i = $i + 1) {
for ($u = 1; $u < 8; $u = $u + 1) {
$urln[] = 'M1s'.[$u].'t'.[$i].'url';
}
}
I am getting an array to string error.
<?php
for ($i = 1; $i < 8; $i++) {
for ($u = 1; $u < 8; $u++) {
$urln[] = 'M1s' . $u . 't' . $i . 'url';
}
}
<?php
$urln = array();
for ($i = 1; $i < 8; $i++) {
for ($u = 1; $u < 8; $u++) {
$urln[] = 'M1s' .$i. 't'. $u .'url';
}
}
foreach ($urln as $i) {
echo "$i\n";
}
?>

For loop extra condition

I have a for loop that goes through a couple of arrays and assigns some values after doing some basic math. My question is: Is there a way to make sure that this for loop ONLY iterates while an additional condition is true?
for ($i = 0; $i < count($ci); $i++) {
$PIDvalue = $ci[$i]["PID"];
$datevalue = $pi[$i]["datetime"];
$pp_tcvalue = $ci[$i]["pp_tc"] - $pi[$i]["pp_tc"];
$pp_trvalue = $ci[$i]["pp_tr"] - $pi[$i]["pp_tr"];
$bp_tcvalue = $ci[$i]["bp_tc"] - $pi[$i]["bp_tc"];
$emailvalue = $ci[$i]["email"];
So I want something like this...
for ($i = 0; $i < count($ci); $i++) {
if($ci[$i]["email"] === $pi[$i]["email"]) {
$PIDvalue = $ci[$i]["PID"];
$datevalue = $pi[$i]["datetime"];
$pp_tcvalue = $ci[$i]["pp_tc"] - $pi[$i]["pp_tc"];
$pp_trvalue = $ci[$i]["pp_tr"] - $pi[$i]["pp_tr"];
$bp_tcvalue = $ci[$i]["bp_tc"] - $pi[$i]["bp_tc"];
$emailvalue = $ci[$i]["email"];
If they don't match, I would assign a value of "0" or something.
You could add an additional condition to the for-loop, making it pretty much unreadable:
for ($i = 0; $i < count($ci), $ci[$i]["email"] === $pi[$i]["email"]; $i++)
but I would rather break the loop:
for ($i = 0; $i < count($ci); $i++) {
if ($ci[$i]["email"] !== $pi[$i]["email"]) break;
$PIDvalue = ...
You can add that in your for condition, like that :
for ($i = 0; $i < count($ci) && $ci[$i]["email"] === $pi[$i]["email"]; $i++) {
When the second condition computes to false, the loop will stop running.

How can i make the for loop parameters dynamic

for ($i=40; $i>=30; $i--) //code will display data for top x row
for ($i=1; $i<=9; $i++) //code will display data for left y column
for ($i=29; $i>=21; $i--) //code will display data for bottom x row
for ($i=30; $i>=39; $i++) //code will display data for right y column
These 4 loops all do the same thing.
In my index.php im using "include" to get the 4 loops that are in 4 different files.
How can I make the for loop dynamic?
Algoritihm:
$i = (40,1,29,30) <--will be any of those 4
$maxlow = (30,9,21,39)
$check =(>,<) <--value depends on whether $i > or < $maxlow
$icrement = (--,++) <-- if $check is > then decrease, otherwise increment
for ($i; $i($check)=$maxlow; $i($increment) <---what i am trying to do
// $step is either 1 (incrementing) or -1 (decrementing)
foreach (range($begin, $maxlow, $step) as $i) {
}
Settings for given loop:
$diff = -1;
$start = 40;
$stop = 30 + $diff;
The loop itself, always like this:
for ($i = $start; $i != $stop; $i += $diff)
$low = [40,1,29,30](rand(0,3);
$high = [30,9,21,39](rand(0,3);
$modifier = ($low > $high) ? -1 : 1;
for($i = $low; ($i * $modifier) < ($high * $modifier); $i += $modifier)
{
doStuff();
}
why not just use for with switch inside, like this:
for ($i=1; $i >=39; $i++) {
switch($i) {
case ($i>=1 && $i<=9):
break;
...
...
case ($i>40):
//do something
break;
}
}
It will be much more readable, and easier to understand/edit in future.

Categories