Php nestedfor loop - php

I have an array in php, and I want to print the elements of the array, 15 at a time, from (n-15). Like, if I have 100 elements in an array, I want to print it 85-100,70-84,55-70,, etc.,
I've tried the loop
for( $j = sizeof($fields)-16; $j < sizeof($fields); ) {
for ( $i = $j ; $i < $i+16 ; $i++ ) {
echo $fields[$i];
echo "<br>";
}
$j=$j-16;
}
but, this prints only the first iternation, i.e 85-100, and goes into an infinite loop.
Where am i going wrong?
Help!

foreach (array_reverse(array_chunk($fields, 15)) as $chunk) {
foreach ($chunk as $field) {
echo $field . '<br />';
}
}

In PHP 5.3, you can do this:
<?php
$fields = range(1, 100);
foreach (array_chunk(array_reverse($fields, true), 15, true) as $i => $chunk) {
echo 'Group ' . $i . ":<br/>\n";
$chunk_rev = array_reverse($chunk, true);
array_walk($chunk_rev, function($value) {
echo "$value<br/>\n";
});
}
See the demo.

Think about the loop termination condition.
If $j is being decremented and $j starts off lower than the comparison value, $j will never be greater than the comparison value, so the loop will never terminate.

Related

Increment number by 1 in foreach loop upto 10

I am trying to increment a value in a foreach loop, but I need it to be maximum 10. How can I do that? My current code is
$i = 0;
foreach ( $signatures as $signature ) {
echo 'Signature ID: ' . $signature . $i;
$i++;
}
Where this foreach loop should stop when the value of $i should reach 10.
Thanks
This would do it.
$i = 0;
foreach ( $signatures as $signature ) {
if($i==10){
break;
}
echo 'Signature ID: ' . $signature . $i;
$i++;
}
Just use break if you want to end any iteration.
Along with breaking the foreach loop at 10, you could just do a for loop:
If $signatures is a numerical array:
for($i = 0; $i < 10; $i++) {
$signature = $signatures[$i];
}
If $signatures is an associative array, access with current() and advance with next():
for($i = 0; $i < 10; $i++) {
$signature = current($signatures);
next($signatures);
}

loop error in php code

Here is my code, and it is not removing $arr[5] element so that I am trying to remove strings starting with # from my array
this is code
<?php
$arr = [
'#EXTM3U',
'#EXTINF:177,Paul Dateh & Oren Yoel - Be More',
'Be More.mp3',
'#EXTINF:291,Christopher Toy - Just Because',
'Just Because.mp3',
'#EXTINF:238,Magnetic North - Drift Away',
'Drift Away.mp3'
];
for ($i = 0; $i <= count($arr); $i++) {
if ($arr[$i]{0} == '#') {
echo $arr[$i] . "\n";
unset($arr[$i]);
}
}
print_r($arr);
?>
Reason:- You are counting array length inside the loop and every time when any value got unset() from the array, length of array decreased and value of count($array) changed (simply decreased)
So logically your 5th and 6th element never goes through if condition (they never get traversed by loop because of decreasing length of the array )
Solution 1:- Put count outside and it will work properly:-
$count = count($arr);
//loop start from 0 so use < only otherwise, sometime you will get an undefined index error
for ($i = 0; $i < $count; $i++) {
if ($arr[$i]{0} == '#') {
//echo $arr[$i] . "\n";
unset($arr[$i]);
}
}
print_r($arr);
Output:-https://eval.in/996494
Solution 2:- That's why i prefer foreach() over for() loop
foreach($arr as $key=> $ar){
if ($ar[0] == '#') {
unset($arr[$key]);
}
}
print_r($arr);
Output:-https://eval.in/996502
more spacific :
for ($i = 0; $i < count($arr); $i++) {
if (strpos($arr[$i], '#') !== false) {
echo "<br/>";
} else {
echo $arr[$i]."<br/>";
}
}
Try to use additional array to push right values. You calc count($arr); each iteration and when you do count($arr); your array gets smaller and count($arr); returns smaller values, so last elements won't be comparing, try to use variable to calc count before loop make changes:
<?php
//...
$start_count = count($arr);
for ($i = 0; $i <= $start_count; $i++) {
if ($arr[$i]{0} == '#') {
echo $arr[$i] . "\n";
unset($arr[$i]);
}
}
Or remove bad element with a help of additional array, put good elements in new array and don't delete them from input array:
<?php
$arr = [
'#EXTM3U',
'#EXTINF:177,Paul Dateh & Oren Yoel - Be More',
'Be More.mp3',
'#EXTINF:291,Christopher Toy - Just Because',
'Just Because.mp3',
'#EXTINF:238,Magnetic North - Drift Away',
'Drift Away.mp3'
];
$cleared_from_mess_array = array();
for ($i = 0; $i <= count($arr); $i++) {
if ($arr[$i]{0} != '#')
{
array_push($cleared_from_mess_array,$arr[$i]);
}
}
print_r($cleared_from_mess_array);
exit;

PHP Loop: Every 4 Iterations Starting From the 2nd

I have an array that can have any number of items inside it, and I need to grab the values from them at a certain pattern.
It's quite hard to explain my exact problem, but here is the kind of pattern I need to grab the values:
No
Yes
No
No
No
Yes
No
No
No
Yes
No
No
I have the following foreach() loop which is similar to what I need:
$count = 1;
foreach($_POST['input_7'] as $val) {
if ($count % 2 == 0) {
echo $val;
echo '<br>';
}
$count ++;
}
However, this will only pick up on the array items that are 'even', not in the kind of pattern that I need exactly.
Is it possible for me to amend my loop to match that what I need?
You can do this much simpler with a for loop where you set the start to 1 (the second value) and add 4 after each iteration:
for ($i = 1; $i < count($_POST['input_7']); $i += 4) {
echo $_POST['input_7'][$i] . '<br />';
}
Example:
<?php
$array = array(
'foo1', 'foo2', 'foo3', 'foo4', 'foo5',
'foo6', 'foo7', 'foo8', 'foo9', 'foo10',
'foo11', 'foo12', 'foo13', 'foo14', 'foo15'
);
for ($i = 1; $i < count($array); $i += 4) {
echo $array[$i] . '<br />';
}
?>
Output:
foo2foo6foo10foo14
DEMO
Try this:
$count = 3;
foreach($_POST['input_7'] as $val) {
if ($count % 4 == 0) {
echo $val;
echo '<br>';
}
$count ++;
}

Continue foreach loop from middle

I have this for each loop:
foreach($downloads as $dl) {
echo seosvelniau2($dl['title']);
}
By default it gives me 50 results, is there any way to split this foreach loop into two (1-25) and (26-50), so I can put both into two separate table columns?
I know, that i can make loop to show only first 25 results like this:
$i=0;
foreach($downloads as $dl) {
$i++;
echo seosvelniau2($dl['title']);
if ($i == 25)
break;
}
but how to do second loop to show (26-50) results?
You can divide the array $downloads even before the loop.(using array_chunk)
$Chunks = array_chunk($downloads , 25);
foreach($Chunks[0] as $dl)
{
//Group 1
}
foreach($Chunks[1] as $dl)
{
///Group2
}
EDIT: Here's a general example: (In case you have more than 50 elements)
$Chunks = array_chunk($downloads , 25);
foreach($Chunks as $oneChunk)
{
//New group of 25 elements.
foreach($oneChunk as $dl)
{
}
}
Two different approaches:
Use each to iterate over the array.
$i = 0;
while(list($id, $item) = each($array)) {
echo $item;
if (++$i == 25) { break; }
}
while(list($id, $item) = each($array)) {
echo $item;
}
If you don't need that array after the loop is complete, you can simply shift the items:
$i = 0;
while (++$i < 25 && count($array)) {
$item = array_shift($array);
echo $item;
}
foreach ($array as $item) {
echo $item;
}
You could switch the columns in between:
$i = 0;
foreach ($downloads as $dl) {
if (++$i === 25) echo '</tr><tr>';
echo seosvelniau2($dl['title']);
}
Another option:
$i=0;
foreach($downloads as $dl) {
$i++;
if ($i <= 25){
//first 25
}else{
//rest
}
}
If you're in the process if drawing an HTML table, and you need to switch td, just do something like this:
for ( $i = 0; $i < count( $downloads ); $i++ )
{
echo seosvelniau2( $downloads[ i ][ 'title' ] );
if ( $i % 25 == 0 )
{
echo( '</td><td>' );
}
}
This will create a new columns every 25 values.
Wouldn't you just use a normal for loop instead of foreach? Then you can determine the start and end points manually, like so.
Then you should have something more or less like this:
for ($i=1; $i<=25; $i++)
{
echo "The number is " . $i . "<br />";
}
for ($i=26; $i<=50; $i++)
{
echo "The number is " . $i . "<br />";
}

push elements to array while in for loop in php

How can I accomplish this in php? there are cases where I need to push more elements to the array that i'm looping through so they also get looped through:
$j = array(1,2,3);
foreach ($j as $i)
{
echo $i . "\n";
if ($i <= 3)
array_push($j, 5);
}
should print 123555 but it stops at 123.
is there a way around this in php?
foreach works on a copy of the array, not the original array (under certain conditions). That's why you're not seeing the changed reflected in the loop.
You will get the expected output when you loop by reference:
foreach ($j as &$i)
{
// ...
}
Output:
1
2
3
5
5
5
Add & to pass the reference. Default a value (copy of $j) is passed.
$j = array(1,2,3);
foreach ($j as $i=>&$v)
{
echo "$i=>$v\n";
if ($i <= 3)
array_push($j, 5);
}
PHP does not support this. From the manual:
As foreach relies on the internal array pointer changing it within the loop may lead to unexpected behavior.
http://php.net/manual/en/control-structures.foreach.php
However, this code will work, although I would not rely on this based on what the manual said.
<?
header( 'content-type: text/plain' );
$j = array(1,2,3);
foreach ($j as &$v )
{
echo "$v\n";
if ($v <= 3)
{
array_push($j, 5);
}
}
Why don't you try while:
$i = 0;
$j = array( 1, 2, 3 );
while ( count( $j ) )
{
echo array_shift( $j );
if ( $i++ <= 3 )
{
array_push( $j, 5 );
}
}

Categories