How to use a while loop instead of a foreach loop - php

I currently have a loop:
foreach($this->rows as $row):
....
endforeach;
Is this possible to put into a while loop?

yes you can do like this
$arr = $this->rows;
$size = sizeof($arr);
$i=0;
while($i<$size)
{
$row = $arr[$i];
// your work
$i+=1;
}

Related

Change foreach loop to a for loop

I'm quite new to PHP. How can I change this foreach loop to only loop twice?
<?php
foreach($results as $row):
?>
Try this code, you just need a counter variable, initialize your counter variable from zero and increment it after each iteration.
<?php
$counter = 0;
foreach($results as $row) {
//your code
if($counter == 1)
{
break;
}
$counter++;
}
?>
You could iterate up to the size of the array or 2 - the smaller of the two.
<?php
$maxInd = min(2, count($results);
for ($i = 0; $i < $maxInd; ++$i) {
$row = $results[$i];
// Do something interesting with $row
}
?>
<?php
for ($i = 0, $count = count($results); $i < $count; ++$i) {
var_dump($results[$i]);
// or assign it to $result variable
$result = $results[$i];
}
?>
But this will work only for collection there are some examples for example generators where you must use foreach.

Can you use a for loop to create array names?

I am pulling data from a database and I want to create array names on the fly.....group1, group2...etc using a for loop. I wonder if this is possible at all? The code below obviously doesn't work and I'm only including it to demonstrate what I'm trying to do. Any help would be much appreciated!
<?php
for ($i=1; $i <=40; $i++){
$group.$i = [];
}
?>
Its not so much "array names" that you are looking for as a much as a nested array. $group[$i] would give you a nested array. eg
for ($i=1; $i <=40; $i++){
$group[$i] = [];
}
$group[1][] = 'foo';
echo $group[1][0];
// prints: foo
Something like this ? This works 100%
// $result = $conn->query($sql);
$i = 0;
$all = array();
while($row = $result->fetch_assoc()) {
$i++;
$arr[$i]['id'] = $row['id'];
$arr[$i]['firstname'] = $row['first_name'];
$arr[$i]['lastname'] = $row['last_name'];
$all[] = $arr[$i];
}
echo '<pre>';
echo print_r($all);

Increment a value inside php foreach?

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

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?

Creating a simple array

I have the following code:
$page=3;
$i=1;
while($i<=$pages) {
$urls .= "'"."http://twitter.com/favorites.xml?page=" . $i ."',";
$i++;
}
What I need to create is this array:
$data = array('http://twitter.com/favorites.xml?page=1','http://twitter.com/favorites.xml?page=2','http://twitter.com/favorites.xml?page=3');
How can I produce an array from the while loop?
$urls = array();
for ($x = 1; $x <= 3; $x++) {
$urls[] = "http://twitter.com/favorites.xml?page=$x";
}
. is for concatenating strings.
[] is for accessing arrays.
[] = pushes a value onto the end of an array (automatically creates a new element in the array and assigns to it).
You can do:
$page=3;
$i=1;
$data = array();
while($i <= $page) {
$data[] = "http://twitter.com/favorites.xml?page=" . $i++;
}
Try this instead:
$page=3;
$i=1;
$url=array();
while($i<=$pages) {
$urls[]="http://twitter.com/favorites.xml?page=".$i ;
$i++;
}
echo("<pre>".print_r($url,true)."</pre>");

Categories