how to limit the number of entries in the for loop php - php

I have a model and ready-made data in a table. In this model, I added a new field and made a connection with another table.
And in order not to manually fill in these fields for each record, I want to create a migration that will automatically fill in this field for all records.
Relationship table has two fields: post_id and author_id.
I am trying to do like this:
$posts = Posts::find()->all();
foreach ($posts as $index => $post) {
for($i = 0, $j = 0; $i < $index; $j++, $i++) {
if ($j >= 4) {
$j = 0;
}
$item = new PostAuthor();
$item->setAttribute('post_id', $posts->id);
$item->setAttribute('author_id', $j + 1);
$item->save();
}
}
Everything also works as it should, but there is one problem, when the counter reaches 4, then the author_id is added again to the same post, starting from one.
I am attaching a screenshot, what should not be circled at all, when the counter reaches 4, then the post does not need to add an author_id anymore

Because
if ($j >= 4) {
$j = 0;
}
does nothing other than set $j = 0. The loop carries on as-written.
If you want the loop to halt here, then you have two options:
foreach ($posts as $index => $post) {
for($i = 0, $j = 0; $i < $index; $j++, $i++) {
if ($j >= 4) {
break;
}
// ...
}
}
or
foreach ($posts as $index => $post) {
for($i = 0, $j = 0; $i < $index, $j < 4; $j++, $i++) {
// ...
}
}
Though at this point $i and $j are functionally identical and you can simply throw one of them away and put an && in the loop boundary condition.
foreach ($posts as $index => $post) {
for($i = 0; $i < $index && $i < 4; $i++) {
// ...
}
}

Related

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.

for loop gets executed just once

I have created an array dynamically like this way
$names = array();
for ($i = 0; $i < 100; $i++) {
$names[] = $i;
}
then created part
$parts = count($names) / 20;
and created a sub array then loop through the parts
$j = 0;
for ($i = 0; $i < $parts; $i++) {
echo "Part" . $i."<br>";
$newarray = array_slice($names, $j, 20);
for ($i = 0; $i < count($newarray); $i++) {
echo $i;
}
$j = $j + 20;
}
The problem is that this code displays from zero to 19 It doesn't display the other parts
Both the inner and outer loops use the same control variable $i, so just change the inner one...
$j = 0;
for ($i = 0; $i < $parts; $i++) {
echo "Part" . $i."<br>";
$newarray = array_slice($names, $j, 20);
for ($i1 = 0; $i1 < count($newarray); $i1++) {
echo $i1;
}
$j = $j + 20;
}

How to compare every value in a for loop?

I have a multidimentional array of 5 items and I want that my loop would compare it like:
1 -> 2, 1 -> 3, 1 -> 4, 1 -> 5, 2->1, 2->3, 2->4, 2->5......// so on and 5 -> 4 in the end.
The problem is that after my array $i value matches 1 and $j value matches 3, the unset is done and the $i value becomes 2 (which is correct) and $j value becomes 4 instead of 3. Could someone tell me why and what I'm doing wrong?
My loop is:
for ($i = 0; $i <= count($myArray); $i++) {
for ($j = $i+1; $j <= count($myArray); $j++) {
if (
// condition 1
&& // condition 2
) {
unset($myArray[$i]);
$i++;
}
}
}
I think that's the problem is when you unset the element in the array, you increment the counter of the loop $i. In this way, the elements of the array that are not configured are removed, this empty array position will be maintained, it will not be reordered, you will have to do it manually or using array_values ​​method.
In the last tour of the array, it will break because you are comparing the number of array elements as equal. You must use index < count($array)
The code would be like this:
for ($i = 0; $i < count($myArray); $i++) {
for ($j = $i+1; $j < count($myArray); $j++) {
if (
// condition 1
&& // condition 2
) {
unset($myArray[$i]);
// $i++;
}
}
}
try something like this
for ($i = 0; $i <= count($myArray); $i++) {
for ($j = 0; $j <= count($myArray); $j++) {
if ($j!=$i)
{
if (
// condition 1
&& // condition 2
) {
unset($myArray[$i]);
$i++;
}
}
}
}
$temp = $myArray;
for ($i = 0; $i <= count($myArray); $i++)
{
for ($j = $i + 1; $j <= count($myArray); $j++)
{
if (
// condition 1
&& // condition 2
)
{
unset($temp[$i]);
$i++;
}
}
}
print_r($temp);
Your result is in $temp. So here indexes wont get hampered, you actually are applying all operation on $temp and normally traversing $myArray.
To be honest, I do not know why nobody has yet advise to use nested foreach, since you all noticed there was a problem with array size.
foreach ($numbers as $number_horizontal_parsing) {
foreach ($numbers as $number_vertical_parsing) {
if ($number_horizontal_parsing != $number_vertical_parsing) {
//do your stuff in your case it seems you want to compare both variables
}
}
}

decrese value of loop

I have this code, but i want in second loop a decrease of $p value. The first internal loop must be repeated three times, the second, two times and the last, one time. I am trying $p-- but without success.
Any idea ? thanks
$p = 3;
for ($i = 0; $i < 3; $i++) {
for ($o = 0; $o < $p; $o++) {
echo "something";
$p--;
}
}
Move your $p-- to outside the inner for loop:
$p = 3;
for ($i = 0; $i < 3; $i++) {
for ($o = 0; $o < $p; $o++) {
echo "something";
}
$p--;
}
Or better, just depend on the value of $i:
for ($i = 0; $i < 3; $i++) {
for ($o = 0; $o < 3 - $i; $o++) {
echo "something";
}
}
Or if you don't actually use $i:
for ($i = 2; $i >= 0; $i--) {
for ($o = 0; $o < $i; $o++) {
echo "something";
}
}
It's quite simple.
for ($i = 2; $i >= 0; $i--)
{
}
Set the starting number at the upper limit number, and then go down until equal to 0, $i minus 1;
You need to decrement $p outside the first loop

php array output problem

In php is there a function to increment the
values of subsequent values twice(*2) in an array
column based on an initial value?
$beta = array(
array('5', '1''1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1'),
array('5','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2'),
array('5','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2'),
array('5','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2'),
array('5','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2'),
array('5','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2'),
array('5','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2'),
array('5','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2'),
array('5','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2'),
array('5','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2')
);
/*Example: '5' will be '10' (5*2 =10 and output 10 to web)
'2' will be '4' (2*2 = 4 and output 4 to web)
The next '2' will be '16' (4*2 = 8 and output 8 to web)
The next '2' will be '32' (8*2 = 16 and output 16 to web)
And so forth? */
Furthermore is there an easier way to construct this array, cause I firmly believe there is, but not something too complicated in terms of construct such that a noob will not understand it, again thanks.
[Disclaimer: I have spent 3 days trying to understand arrays, I now understand them; however, I am still new and am currently having some issues when trying to manipulate the values in my array and output them to the web.And I am still pretty sure I have a lot to read and learn, so please no flamers, I just need some help, found this problem in this C++ book:
[http://books.google.com/books?id=4Fn_P7tdOZgC&pg=PT424&lpg=PT424&dq=subsequent+++column+is+twice+the+value&source=bl&ots=gSvQ_LhxoI&sig=dG_Ilf1iLO86lqX936cT1PpkPc8&hl=en&ei=OEEBS_eODYyotgOFtJD3CQ&sa=X&oi=book_result&ct=result&resnum=1&ved=0CAgQ6AEwAA#v=onepage&q=subsequent%20%20%20column%20is%20twice%20the%20value&f=false][1]
You can try array_map:
<?php
function increase($n) {
return is_array($n) ? array_map('increase', $n) : $n * 2;
}
$new_beta = array_map("increase", $beta);
As for constructing the array, there are other methods to do so but I believe this is the most performent and clean.
Here is an answer for each question in that section of the book, enjoy!
<?php
// Declare an array alpha of 10 rows and 20 columns of type int
// Initialise the array alpha to 0
$alpha = array(array());
for($i = 0; $i < 10; $i++)
{
for($j = 0; $j < 20; $j++)
{
$alpha[$i][$j] = 0;
}
}
// Store 1 in the first row and 2 in the remaining rows
for($i = 0; $i < 10; $i++)
{
for($j = 0; $j < 20; $j++)
{
if($i == 0)
{
$alpha[$i][$j] = 1;
}
else
{
$alpha[$i][$j] = 2;
}
}
}
// Store 5 in the first column, and make sure that the value in
// each subsequent column is twice the value in the previous column
// (Beware this doesn't build off the initial value of 5 in the first
// column but the previously set values above)
for($i = 0; $i < 10; $i++)
{
for($j = 0; $j < 20; $j++)
{
if($j == 0)
{
$alpha[$i][$j] = 5;
}
else
{
if($j - 1 >= 1)
{
$alpha[$i][$j] = $alpha[$i][$j-1] * 2;
}
}
}
}
// Print the array alpha one row per line
print "Printing the array alpha one row per line:<br/>";
for($i = 0; $i < 10; $i++)
{
for($j = 0; $j < 20; $j++)
{
print "[". $alpha[$i][$j] ."] ";
}
print "<br/>";
}
print "<br/>";
// Print the array alpha one column per line
print "Printing the array alpha one column per line:<br/>";
for($j = 0; $j < 20; $j++)
{
for($i = 0; $i < 10; $i++)
{
print "[". $alpha[$i][$j] ."] ";
}
print "<br/>";
}
?>

Categories