Increment a value inside php foreach? - php

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

Related

php foreach loop

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);
}
?>

foreach output a set number of arrays only

How would I output only a set of numbers in an array, say if theres 10 arrays, I would only like to output 8 of them?
foreach($arrays as $array){
//do I use a for loop/
}
Thanks!
foreach is only the natural approach if you actually want to iterate over each item (as the name implies). However, you could do something like this:
$i = 0;
foreach($arrays as $array){
...
$i++;
if ($i == $limit) {
break;
}
}
$i = 0;
foreach($arrays as $array){
if($i < 8){
// do something
}
$i++;
}
foreach(array_slice($arrays, 0, 8) as $array){
//do I use a for loop/
}
You could use a foreach loop like this (already mentioned).
$i = 0;
foreach($arrays as $array){
//do I use a for loop/
if(++$i >= 8) break;
}
...or you can use a for loop, which is designed for doing actions a set number of times, e.g., 8 times.
for($i=0; $i < 8; $i++){
$array = $arrays[$i];
// body
}

Skip a number of iterations during foreach

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.

Problem on adding a counter to a code with 3 foreach loops

I am having trouble on adding a counter starting from 1 to the following piece of code, near echo $images;
I would like to count how many times it echoes $images. My purpose i to add the number next to images.
Any help would be great! Please have in mind if there is a way of making the following code better. Thank you!
foreach($items as $item) {
$descr = $xPath->query('./description', $item);
foreach ($descr as $d) {
$temp_dom = new DOMDocument();
$temp_dom->loadHTML( $d->nodeValue );
$temp_xpath = new DOMXPath($temp_dom);
$img = $temp_xpath->query('//div[#class="separator"]//img');
foreach ($img as $imgs) {
$images=$imgs->getAttribute('src');
echo $images; }
}
}
Initialize a variable, e.g. $count = 0;, and then add 1 on each loop:
foreach ($img as $imgs) {
$images=$imgs->getAttribute('src');
++$count; // <= here you go
echo $images; }
foreach don't maintain its own counter, if you want a counter you can use the for loop instead
for ($i = 0; $i <= count($img).; $i++) {
$images = $img[i]->getAttribute('src');
echo $images;
}
Or you can just initialize your own counter in the foreach
foreach($img as $imgs) {
$i = 1;
$images = $imgs->getAttribute('src');
echo $images;
$i++;
}
Can't you just add something like
$counter = 0;
before the firsrt foreach, and then somethin like
$counter++;
echo $images;
echo $counter;
just increase counter at same time, you echo $images. Or am I missing something?

PHP array printing using a loop

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 :)
}

Categories