I would like to skip a number of iterations of a foreach loop.
I have this code;
$myarray = array("a","b","c","d","e","f","g","h");
$skip = 5;
foreach($myarray as $key => $letter){
if($key < $skip){
$key = $skip;
}
echo $letter;
}
This code doesn't do the trick. But with it I can sort of explain what I want. I what to actually move the pointer of the next iteration. It thought that by modifying the value of the key to the one i want would be enough. I understand that a possible solution would be this.
$myarray = array("a","b","c","d","e","f","g","h");
$skip = 5;
foreach($myarray as $key => $letter){
if($key < $skip){
continue;
}
echo $letter;
}
But that kinda still does the iteration step. I would like to completely jump over the iteration.
Thanks
See: array_slice
$myarray = array("a","b","c","d","e","f","g","h");
foreach(array_slice($myarray, 5) as $key => $letter){
echo $letter;
}
You could just use a for loop instead
EDIT:
for($i = $skip; $skip > 0, $i < count($myarray); $i++) {
// do some stuff
}
That's not really how foreach loops (and iteration in general) work.
You can either do the continue version (which works fine; if it's the first thing in the loop body, it's essentially the same), or you can construct a different array to iterate over that doesn't include the first elements, or you can use a regular for loop.
<?php
$myarray = array("a","b","c","d","e","f","g","h");
$skip = 5;
$index = 0 ;
foreach($myarray as $key => $letter){
if( ($index % $skip) == 0 ){
echo $letter;
}
$index++;
}
?>
$myarray = array("a","b","c","d","e","f","g","h");
foreach (new LimitIterator (new ArrayIterator ($myarray), 5) as $letter)
{
echo $letter;
}
foreach (array_slice($myarray, 5) as $key => $letter) {
[...]
}
You can call $array->next() for $skip times. There are cases when you cannot easily use a regular for loop: for example when iterating a DatePeriod object.
Related
is it possible to start a foreach loop from specific element [sixth element]?
im using this code:
<?php
$num=1;
foreach($temp_row as $key => $value) {
echo $num;
$num++;
}
?>
thanks :)
You can use for example array_slice()
$num = 5; //it will start from sixth element
foreach(array_slice($temp_row, $num) as $key => $value) {
echo $key.'=>'.$value.'<br>';
}
Not directly with a foreach(). The clue is in the each part of the name. It loops through all elements.
So how can we achieve it?
You could always just have an if() clause inside the loop that checks the key value before doing the rest of the work.
But if that's not workable for you, for whatever reason, I'd suggest using a FilterIterator to achieve this.
The FilterIterator is a standard PHP class which you can extend to create your own filters. The iterator can then be looped using a standard foreach() loop, picking up only the records that are accepted by the filter.
There are some examples on the manual page linked above that will help, but here's a quick example I've thrown together for you:
class SkipTopFilter extends FilterIterator {
private $filterNum = 0;
public function __construct(array $array, $filter) {
parent::__construct(new ArrayIterator($array));
$this->filterNum = $filter;
}
public function accept() {
return ($this->getInnerIterator()->key() >= $this->filterNum);
}
}
$myArray = array(13,6,8,3,22,88,12,656,78,188,99);
foreach(new SkipTopFilter($myArray, 6) as $key=>$value) {
//loop through all records except top six.
print "rec: $key => $value<br />";
}
Tested; outputs:
rec: 6 => 12
rec: 7 => 656
rec: 8 => 78
rec: 9 => 188
rec: 10 => 99
you could skip if counter is not 6th element...
<?php
$num=0;
foreach($temp_row as $key => $value) {
if( ++$num < 6 )
{
continue;
}
echo $num;
}
?>
Or with a for loop
$num = 1;
for($i=5; $i<= count($temp_row), $i++) {
echo $num;
$num++;
}
try this code:
$new_temp_row = array_slice($temp_row, 5);
foreach($new_temp_row as $key => $value) {
echo $value;
}
You may create new array with needed data part of origin array and work with it:
$process = array_slice ($temp_row, 5);
foreach($process as $key => $value) {
//TODO Your logic
}
Or you may skipp first siel elments:
<?php
$num=1;
foreach($temp_row as $key => $value) {
if ($num < 6) {
$num++;
continue;
}
//TODO Your logic
}
?>
I suggest you use a for look instead of a for each. You can then access both the key and value that are at i position inside your loop.
<?php
$num = 1;
$keys = array_keys( $temp_row );
for( $i = 5; $i < count( $temp_row ); $i++ ) {
$key = $keys[$i];
$val = $temp_row[$i];
echo $i;
}
?>
$i = 1;
foreach ($temp_row as $key => $value) {
if (($num = $i++) < 6) continue;
// Do something
}
Or
for ($i = 0; $i < 5; $i++) next($temp_row);
while(list($key, $value) = each($temp_row)) {
// Do something
}
Is it possible to increment a php variable inside a foreach?
I know how to loop by declaring outside.
I'm looking for something like the syntax below
foreach ($some as $somekey=>$someval; $i++)
{
}
No, you will have to use
$i = 0;
foreach ($some as $somekey=>$someval) {
//xyz
$i++;
}
foreach ($some as $somekey=>$someval)
{
$i++;
}
lazy way of doing is:
{
$i=1;
foreach( $rows as $row){
$i+=1;
}
}
,but you have to scope foreach for $i to dont exist after foreach or at last unset it
$i=1;
foreach( $rows as $row){
$i+=1;
}
unset($i);
, but you should use for cycle for that as leopold wrote.
$dataArray = array();
$i = 0;
foreach($_POST as $key => $data) {
if (!empty($data['features'])) {
$dataArray[$i]['feature'] = $data['features'];
$dataArray[$i]['top_id'] = $data['top_id'];
$dataArray[$i]['pro_id'] = $data['pro_id'];
}
$i++;
}
I know it is an old one here, but these are my thoughts to it.
$some = ['foo', 'bar'];
for($i = 0; $i < count($some); $i++){
echo $some[$i];
}
-- Update --
$some = ['foo', 'bar'];
$someCounted = count($some);
for($i = 0; $i < $someCounted; $i++){
echo $some[$i];
}
It would achieve, what you are looking for in first place.
Yet you'd have to increment your index $i.
So it would not save you any typing.
Is there any reason not to use
foreach ($some as $somekey=>$someval)
{
$i++;
}
?
foreach ($some as $somekey=>$someval)
{
$i++;
}
foreach ($some as $somekey=>$someval)
{
$i++;
}
i is just a variable. Even though it's used to iterate over whatever item you're using, it can still be modified like any other.
This will do the trick!
Remember that you'll have to define $i = 0 before the foreach loop if you want to start counting/incrementing from 0.
$i = 0;
foreach ($some as $somekey=>$someval) {
$i++;
}
Unfortunately, this is not possible. I was looking for an elegant way to do this, very similar to this:
for ($k = 0 ; $k < $columns; $k++){ echo '<td></td>'; }
This works for the for functionality in PHP, but then you would have to pull the item, such as $columns[$k], and then you're back to a less than ideal situation.
Reference
I have two arrays in my code.
Need to perform a foreach loop on both of these arrays at one time. Is it possible to supply two arguments at the same time such as foreach($array1 as $data1 and $array2 as $data2)
or something else?
If they both the same keys, you can do this:
foreach($array1 as $key=>data1){
$data2 = $array2[$key];
}
Assuming both have the same number of elements
If they both are 0-indexed arrays:
foreach ($array_1 as $key => $data_1) {
$data_2 = $array_2[$key];
}
Otherwise:
$keys = array_combine(array_keys($array_1), array_keys($array_2));
foreach ($keys as $key_1 => $key_2) {
$data_1 = $array_1[$key_1];
$data_2 = $array_2[$key_2];
}
Dont use a foreach. use a For, and use the incremented index, eg. $i++ to access both arrays at once.
Are both arrays the same size always?
Then this will work:
$max =sizeof($array);
for($i = 0; $i < $max; $i++)
array[$i].attribute
array2[$i].attribute
If the arrays are different sizes, you may have to tweak your approach. Possibly use a while.
iterative methods:
http://php.net/manual/en/control-structures.while.php
http://php.net/manual/en/control-structures.for.php
http://php.net/manual/en/control-structures.do.while.php
use for or while loop e.g.
$i = 0;
while($i < count($ar1) && $i < count($ar2) ) // $i less than both length !
{
$ar1Item = $ar1[$i];
$ar2Item = $ar2[$i];
$i++;
}
No to my knowledge with foreach, but can be easily done with for:
<?php
$cond1 = 0<count($array1);
$cond2 = 0<count($array2);
for ($i=0;$cond1 || $cond2;$i++)
{
if ($cond1)
{
// work with $array1
}
if ($cond2)
{
// work with $array2
}
$cond1 = 0<count($array1);
$cond2 = 0<count($array2);
}
?>
Here's my array:
$array = array(1,2,3,4,5,6,7,8,9,10);
I want to iterate through the array 5 times, do something else, then resume iteration where I left off.
foreach ($array as $value) {
//do something until key 5
}
//do something else now
//resume...
foreach ($array as $value) {
//key should start at 6
}
How can I do this? Is there a way to achieve this with a foreach loop?
Update: I realized it would be silly to repeat the same code twice. The reason I was asking this is because I'm using a foreach loop to display table rows. I wanted to display the first five and hide the rest. So this is what I ended up with:
<?php
$counter = 1;
foreach ($array as $object): ?>
<?php if ($counter > 5): ?>
<tr style="display: none;">
<?php else: ?>
<tr>
<?php endif; ?>
<td><?php echo $object->name; ?></td>
</tr>
<?php $counter++; ?>
<?php endforeach; ?>
You need to use PHP's internal array pointer.
Something like:
$arr = range(0, 9);
for($i = 0; $i < 5; $i++) {
print current($arr);
next($arr);
}
//the pointer should be half way though the array here
something like this:
$counter = 0;
foreach ($array as $value)
{
if($counter == 5)
{
do something random;
$counter++;
continue;
}
//do something until key 5
$counter++;
}
Just curious, but wouldn't calling a function in the array to do what you need done achieve the same result?
Use two arrays:
$first_five = array_slice($array, 0, 5);
$remainder = array_slice($array, 5);
Is there a reason you need to do this with foreach, as opposed to just for?
you can use each() to resume iterating.
$a = array(1,2,3,4);
foreach ($a as $v) {
if ($v == 2) break;
}
while (list($k, $v) = each($a)) {
echo "$k = $v\n";
}
I think jspcal had the best answer so far. The only modification I made to his code was to use a do-while loop instead, so it would not skip the element where first loop breaks.
$arr = array(1,2,3,4);
// Prints 1 2
foreach($arr as $v)
{
if ($v == 3)
{
break;
}
echo "$v ";
}
// Prints 3 4
do
{
echo "$v ";
}
while( list($k, $v) = each($arr) );
(For the problem as stated I wouldn't recommend it but:) You can also use the NoRewindIterator.
$array = array(1,2,3,4,5,6,7,8,9,10);
$it = new NoRewindIterator(new ArrayIterator($array));
foreach($it as $x) {
echo $x;
if ($x > 4) {
break;
}
}
// $it->next();
echo 'taadaa';
foreach($it as $x) {
echo $x;
}
prints 12345taadaa5678910.
(Note the duplication of the element 5. Uncomment the $it->next() line to avoid that).
It's a little kloodgy, but it should work:
foreach($array as $key => $value)
{
$lastkey = $key;
// do things
if($key == 5) break;
}
// do other things
foreach($array as $key => $value)
{
if($key <= $lastkey) continue;
// do yet more things
}
If I know the length of an array, how do I print each of its values in a loop?
$array = array("Jonathan","Sampson");
foreach($array as $value) {
print $value;
}
or
$length = count($array);
for ($i = 0; $i < $length; $i++) {
print $array[$i];
}
Use a foreach loop, it loops through all the key=>value pairs:
foreach($array as $key=>$value){
print "$key holds $value\n";
}
Or to answer your question completely:
foreach($array as $value){
print $value."\n";
}
for using both things variables value and kye
foreach($array as $key=>$value){
print "$key holds $value\n";
}
for using variables value only
foreach($array as $value){
print $value."\n";
}
if you want to do something repeatedly until equal the length of array us this
// for loop
for($i = 0; $i < count($array); $i++) {
// do something with $array[$i]
}
Thanks!
Here is example:
$array = array("Jon","Smith");
foreach($array as $value) {
echo $value;
}
foreach($array as $key => $value) echo $key, ' => ', $value;
I also find that using <pre></pre> tags around your var_dump or print_r results in a much more readable dump.
either foreach:
foreach($array as $key => $value) {
// do something with $key and $value
}
or with for:
for($i = 0, $l = count($array); $i < $l; ++$i) {
// do something with $array[$i]
}
obviously you can only access the keys when using a foreach loop.
if you want to print the array (keys and) values just for debugging use var_dump or print_r
while(#$i++<count($a))
echo $a[$i-1];
3v4l.org
Another advanced method is called an ArrayIterator. It’s part of a wider class that exposes many accessible variables and functions. You are more likely to see this as part of PHP classes and heavily object-oriented projects.
$fnames = ["Muhammed", "Ali", "Fatimah", "Hasan", "Hussein"];
$arrObject = new ArrayObject($fnames);
$arrayIterator = $arrObject->getIterator();
while( $arrayIterator->valid() ){
echo $arrayIterator->current() . "<br />";
$arrayIterator->next();
}
If you're debugging something and just want to see what's in there for your the print_f function formats the output nicely.
Additionally, if you are debugging as Tom mentioned, you can use var_dump to see the array.
Foreach before foreach: :)
reset($array);
while(list($key,$value) = each($array))
{
// we used this back in php3 :)
}