I know how to count elements inside a loop, but tried and can´t find a solution. Actually, I can count the elements in loop in this way:
$i = 0;
foreach ($Contents as $item)
{
$i++;
}
echo $i;
But in my case, I have large function and I can do this, but need more time for count elements inside. I can´t put the string for showing number elements inside loop outside of the function. I must show inside loop all number of elements and show as this. Here's an example:
$i = 0;
foreach ($Contents as $item)
{
print "Number Elements it´s : $i";
print "Element ".$i."<br>";
$i++;
}
The problem here is that the phrase "number elements it´s" always repeats, because inside loop, and all time $i show me 0,1,2,3,4,5 ...... and all time the same as number of elements inside loop.
My idea and question is if it´s possible inside loop to show the number of elements and after this show the elements as this structure when executing the script:
Númber elements it´s : 12
Element 1
Element 2
Element 3
.
.
.
.......
This it´s my question. I hope you understand it all. Thanks in advance.
As mentioned in the comments, youu will need to use the count() function for that. If you insist on having it inside the loop, simply do it like this:
$i = 0;
foreach ($Contents as $item)
{
if($i == 0) {
print "Number of Elements is : " . count($Contents) . "<br><br>";
}
print "Element ".$i."<br>";
$i++;
}
Related
I want to show a content of variable whom been calculate in a foreach loop. The problem is that I want to echo it before the loop.
<?php
echo $total; // note this line I want to appear the total count of loop. the problem is it cannot appear because it is in the above of foreach loop. I want to appear it in this above before foreach loop.
$total = 0;
foreach($pathList as $item) {
$fileInfo = pathinfo($item);
if(preg_match(strtolower('/\b'.$_POST['song'].'\b/'), strtolower($filename))) {
$total = $total + 1; // the total count of foreach loop I want to appear in echo $total
}
// some code
}
?>
I do want to echo it inside the loop but only once after completed the loop.
Any idea how do I solve this problem? I tried global $total but not working...
Thanks in advance!
Generally - NO. You cannot echo variable that not been calculate yet (synchronization in PHP).
If all you do in the for-loop regarding $total is increasing by 1 then you actually count the number of element in the array so you can just do:
echo count($pathList);
Before the for-loop. Documentation in here
Updated:
If $total is affected in the loop (as you updated the question) then I believe best practice will be to counting array element first (without executing any more code), then echo the $total, afterward, loop on the original data and execute the rest of your code.
$total = 0;
foreach($pathList as $item) {
$fileInfo = pathinfo($item);
if(preg_match(strtolower('/\b'.$_POST['song'].'\b/'), strtolower($filename))) // or what ever condition you have to check for total
$total = $total + 1;
}
echo count($total); // give you the count you need
foreach($pathList as $item) {
// exec the rest of your code
}
This may run at O(2*n) but its not worse
It is not possible. Lines are executed in the order in which they appear in the script.
The value of $total at the end of the loop is equal to the value of count($pathList)
If you need the value of the last iterated element of the $pathList before the execution of the loop, then it can be echoed as
echo $pathList[count($pathList)-1];
In essence, I have 3 arrays. These are serialised, stored to the DB, un-serialised and then outputted to a page. myFirstArray, mySecondArray, & myThirdArray.
From what I gather - I need to be using a foreach loop, or a for loop with a counter, as the 3 arrays are all of (the same) unknown length. By that I mean one user may have stored 4 items into each of the 3 arrays, but another user might have stored 8 items into each of the 3 arrays.
I'm trying to get the output to look something like this:
myFirstArray[0], mySecondArray[0], myThirdArray[0]
myFirstArray[1], mySecondArray[1], myThirdArray[1]
myFirstArray[2], mySecondArray[2], myThirdArray[2]
The current code I have is as follows:
foreach ($myFirstArray as $value1){
echo $value1 . " ";
}
foreach ($mySecondArray as $value2){
echo $value2 . " ";
}
foreach ($myThirdArray as $value3){
echo $value3 . "<br>";
}
I am aware that this code is never going to output my arrays as I would like, but I'm having some difficulty with working out the logic behind what I need. I haven't rushed straight to StackOverflow to ask, but nothing else I've seen has been very helpful!
Since both arrays have the same length, I propose
$length = count($myFirstArray);
for($i = 0; $i <$length ; $i++) {
echo $myFirstArray[$i].','.$mySecondArray[$i].','.$myThirdArray[$i].'<br/>';
}
This will loop through all of your arrays at the same time :) .
How do you count the results inside a foreach then store that value in a variable to be used on another foreach.
Example. This foreach returns 5 items
foreach ($xml->items as $item) {
echo "$item->name";
echo "$item->address";
}
Now I want that the foreach above be counted and stored in say $totalitems and be used on another foreach. This second foreach also counts its results and store in $totalitems2. Something like this:
foreach ($xml->items as $item) { //Same source but they will be displayed separately based on a condition.
echo "$item->name";
echo "$item->address";
if_blah_blah_meet_condition_then_break;
}
So basically what I want here is to restrict the total number of items being displayed on both foreach combined. $totalitems and $totalitems2 should have the sum of 8. 8 is the number I want limit the items returned. Doesn't matter if the other foreach has more items than the other. 3 and 5. 4 and 4. 6 and 2. Etc.
How can I achieve this? Please advice.
Just use the simple iterator ++ methods. When you are on the second foreach, watch for when $i passes the number that you want to stop it.
Code:
$i = 0;
foreach ($xml->items as $item) {
echo "$item->name";
echo "$item->address";
$i++;
}
foreach ($xml->items as $item) {
echo "$item->name";
echo "$item->address";
$i++;
if ($i > 5) { // or whatever the number is
break;
}
}
$totalItems = count($xml->items);
foreach ($xml->items as $item) {
echo "$item->name";
echo "$item->address";
}
Just use count($xml->items) and that value in the condition, inside the loop.
It seems your array is stored in xml->items therefor, you only would have to save it in another variable if you want to store it.
foreach ($xml->items as $cont=>$item) {
echo "$item->name";
echo "$item->address";
if($cont<8){
$totalItems_one[] = $item;
}
}
//whatever changes you do to $xml->items
foreach ($xml->items as $cont=>$item) {
echo "$item->name";
echo "$item->address";
if($cont<8){
$totalItems_two[] = $item;
}
}
Like this you have the two new arrays totalItems_one and totalItems_two and you can get the number of items just doing count($totalItems_one) or count($totalItems_two) whenever you want.
I'm trying to figure out if I need to do this inside the for loop or outside the for loop but I want to check to see its empty or not first.
echo "<ul>";
for($x = 0; $x <= (count($quotesArray)-1); $x++)
{
echo "<li>".stripslashes($quotesArray[$x]->quote)."</li>";
}
echo "</ul>";
There is something simpler that checking during loop - it filters all the values and is called array_filter() function:
$quotesArray = array_filter($quotesArray);
echo "<ul>";
foreach($quotesArray as $quote){
echo "<li>".stripslashes($quote)."</li>";
};
echo "</ul>";
The above assumes that $quotesArray contains strings (or elements that work correctly in string context) and you do not want only the elements that are evaluated as false when converted to boolean (see more about converting to boolean).
Additionally you can simplify your code further:
$quotesArray = array_filter($quotesArray);
$quotesArray = array_map('stripslashes', $quotesArray);
echo '<ul><li>'.implode('</li><li>', $quotesArray).'</li></ul>';
if you know $quotesArray contains at least one element.
EDIT:
Short version, that also checks whether the list should be generated (in other words: whether array contains at least one element after processing):
$quotesArray = array_map('stripslashes', array_filter($quotesArray));
if (!empty($quotesArray)) {
echo '<ul><li>'.implode('</li><li>', $quotesArray).'</li></ul>';
};
It needs to be outside the loop because if it is empty, and you don't generate any list items, then you have no list, so you should not generate the ul start and end tags either (since a list with no list items is invalid).
well if you dont wan the list at all then you should do it before the echoing of the first <ul>
if(count($quotesArray) > 0){
//Do your echos and loops in here
}
You can just run both checks.
if($quotesArray){
echo '<ul>';
foreach ($quotesArray as $quote) {
if ($quote) {
echo '<li>' . stripslashes($quote->quote) . '</li>';
}
}
echo '</ul>';
}
When you say you want to check if it's empty, do you mean the entire $quotesArray or one of the values within it?
If you mean you want to check if a value within the array is empty, you could consider this approach:
echo '<ul>';
foreach ($quotesArray as $quote) {
if ($quote) {
echo '<li>' . stripslashes($quote) . '</li>';
}
}
echo '</ul>';
If I have a foreach construct, like this one:
foreach ($items as $item) {
echo $item . "<br />";
}
I know I can keep track of how many times the construct loops by using a counter variable, like this:
$counter = 0;
$foreach ($items as $item) {
echo $item.' is item #'.$counter. "<br />";
$counter++;
}
But is it possible to do the above without using a "counter" variable?
That is, is it possible to know the iteration count within the foreach loop, without needing a "counter" variable?
Note: I'm totally okay with using counters in my loops, but I'm just curious to see if there is a provision for this built directly into PHP... It's like the awesome foreach construct that simplified certain operations which are clunkier when doing the same thing using a for construct.
No it's not possible unless your $items is an array having contiguous indexes (keys) starting with the 0 key.
If it have contiguous indexes do:
foreach ($items as $k => $v)
{
echo $k, ' = ', $v, '<br />', PHP_EOL;
}
But as others have stated, there is nothing wrong using a counter variable.
There's no easier way - that's kinda what count variables are for.
I'm assuming that you want to know the current count during the loop. If you just need to know it after, use count($items) as others have suggested.
You could tell how many time it WILL loop or SHOULD have looped by doing a
$loops = count($items);
However that will only work if your code does not skip an iteration in any way.
foreach loops N times, where N is just the size of the array. So you can use count($items) to know it.
EDIT
Of course, as noticed by Bulk, your loop should not break (or maybe continue, but I would count a continue as a loop, though shorter...)