Hi,
I am trying to output the total value of $i outside the loop. What's the best way to go about this?
echo $i; // need to echo this, in this case, value would be '3' $id = array("12","34","645"); foreach($id as $items) { echo $items.'<br />'; $i++; }
Thank you!
count() on the array would be esier
I can't use count in my case. Is there any other way?
I will post my code if it is of any help.
Thanks
EDIT: I can't use count because some of the values in my array should not be included in my count.
you should just be able to echo $i after the loop
maybe you could initialise $i=0; before the loop
What would $i begin and end with, in the case you posted?
If it begin with 3, it would be 6 at the end of loop
$i should be 0, I suppose.
I want $i to be equal to '3' when it's done looping.
echo 'Total items in array: '.$i; $id = array("12","34","645"); foreach($id as $items) { echo $items.'<br />'; $i++; }
Initialize it to 0 before the loop, and then it should work fine.
In your first post, you tried to echo $i before anything had been done with it. Can't put the cart in front of the horse. 😉
im guessing its just a display issue were you want the count to appear before the looped output.
so something like this would work
$id = array("12","34","645"); $out=''; foreach($id as $items) { $out.= $items.'<br />'; $i++; } echo 'Total items in array: '.$i; echo $out;
Dragon, that is exactly what I am trying to do.
I have while with a mysql_query in my foreach getting values from my db, include divs, etc. I need to print the total count at the top of everything.
I will try your suggestion and report back, thanks.
$query1 = "SELECT DISTINCT propertyID FROM listings"; $result1 = mysql_query($query1) or die(mysql_error()); while ($row = mysql_fetch_array($result1)) { $propertyID = array($row['propertyID']); foreach($propertyID as $ID) { $query = "SELECT * FROM calendar WHERE date BETWEEN '$start' AND '$end' AND propertyID=$ID"; $result = mysql_query($query) or die(mysql_error()); $numrows = mysql_num_rows($result); if($numrows == 0) { echo 'print '.$ID.'<br />'; } } }
This is a simplified version of my code. I only want to count the items if they match the "if($numrows ==0)" condition.
its often best to do all processing first and assign any output to a var(s) to be outputted at the end.
I am not getting anywhere. I have tried using sessions, but I have to refresh the page to update the count.
🙁
i don't know why you would uses sessions unless you want the output on another page, in the while loop assign the output to a var rather than echoing it as i showed, and add your $i loop counter