I'm having trouble working with a foreach loop in my PHP script. I have retrieved an array of records from a database search and I now want to get the total for one of the fields in the found set of records. Here's my code so far:
foreach($result->getRecords() as $record){
$recordTotal = $record->getField('products_total');
$salesToday = $salesToday + $recordTotal;
}
If 5 records were found and the value of the 'products_total' field was:
1
2
3
4
5
I want to get the total of these (15) and store that in the $salesToday variable. The $salesToday variable doesn't exist prior to this foreach loop.
Can anyone spot the error in my code? If I echo $salesToday after the loop I get 0 instead of 15.
Check if $recordTotal has values in all the iterations. Maybe is always 0.
$recordTotal = 0;
foreach($result->getRecords() as $record){
$recordTotal = $record->getField('products_total');
$salesToday += $recordTotal;
}
You can try that code, but is the same code that you are using, with the $recordTotal var initialized.
Maybe initialize the $salesToday variable before the for each loop?
$salesToday = 0;
EDIT:
$salesToday = 0;
foreach($result->getRecords() as $record){
$salesToday += $record->getField('products_total');
}
$salesToday=0;
foreach($result->getRecords() as $record){
$salesToday += $record->getField('products_total');
}
echo 'Today sales:'.$salesToday.'<br/>';
Declare the $salesToday before the loop. Each loop iteration won't remember the value before.
The reason for this is a form of automatic memory management called garbage collection. In it's simplest form, the garbage collector will free up memory that isn't being used anymore.
In this example the $salesToday variable is only declared within the loop so it expects the variable to only ever be used in that loop. Say for example you had another loop surrounding everything you had there. If you declared the variable in the 2nd loop, it would only be available in the 2nd and 3rd loops and not the 1st. The same goes for functions/method, if statements etc.
Turns out to be an issue with my access privileges and not being able to view some of the values from the database record. These posts helped me locate the issue and correct the syntax issue with my loop.
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];
i've a array problem couldn't just solve it:
here's the code that is already in a foreach loop. i'm getting the $row->class_id value from this loop. it works fine and get me the total students row within an array and i preserved it in $total_student_of_this_class variable. i used another foreach loop for storing the result of first loop and then second loop and so on. but this loop gives only first loop result.
i need to combine the all array of total iteration of the loop.
$total_student_of_this_class =
$this->db->select('student_id')->where('class_id',
$row->class_id)->get('student')->result_array();
echo count($total_student_of_this_class);
// prints 2 in the first row of the output table and 5 in the second
row for me.
$total_student = array();
foreach ($total_student_of_this_class as $tt)
{
$total_student[] = $tt;
}
echo '<pre>';
print_r($total_student_of_this_class);
echo '</pre>'
echo count($total_student);
// prints only 2 outside the loop (not 7)
pls someone help me.
The problem here is seems to be with $total_student = array();: initializing array inside an other loop it always starts it from zero values array, so you get only results from one iteration inside it and doesn't collect all datas.
You can also look at array_merge php function.
I am trying to get the total number of bikes available in a bike share system. I am using php and simpleXML to filter the XML data.
I have successfully retrieved the number of bikes at each station.
foreach ($xml->station as $items) {
print $items->nbBikes;
}
But I want the total number of bikes available at all stations. I tried this to declare a variable ($totalBikes) that added to itself each time through the foreach statement, but it did not work.
foreach ($xml->station as $items) {
print $items->nbBikes;
$numberOfBikes = $items->nbBikes;
$totalBikes= $numberOfBikes += $numberOfBikes;
}
print $totalBikes;
Can anyone please suggest a way to get the total number of bikes?
Thanks!
You want to add $numberofbikes to $totalbikes, not to itself:
$totalBikes += $numberOfBikes;
which is a shortcut version of
$totalBikes = $totalbikes + $numberOfBikes;
Be sure you're declaring '$totalbikes' before your foreach loop though so it doesn't get reset on each iteration.
You declared $totalBikes within the loop, so it is getting reset every time you iterate. Also, you're not adding $numberOfBikes to $totalBikes properly. Try this:
$totalBikes = 0;
foreach ($xml->station as $items) {
$numberOfBikes = $items->nbBikes;
$totalBikes += $numberOfBikes;
}
print $totalBikes;
Instead of iterating, use xpath:
$bikes = $xml->xpath("/stations/station/nbBikes");
$sum = array_sum(array_map("intval", $bikes));
line 1 will select all <nbBikes> into an array, but as SimpleXml objects
line 2 will first transform all elements to Integer, then add them up.
Note: For a one-liner, there's a sum-function in xpath, but I couldn't get it to work. Any ideas why?
$sum = $xml->xpath("sum(/stations/station/nbBikes)")[0];
I need to get all the elements from a textarea in a HTML form and insert them into the MySQL database using PHP. I managed to get them into an array and also find the number of elements in the array as well. However when I try to execute it in a while loop it continues displaying the word "execution" (inside the loop) over a 1000 times in the page.
I cannot figure out what would be the issue, because the while loop is the only applicable one for this instance
$sent = $_REQUEST['EmpEmergencyNumbers'];
$data_array = explode("\n", $sent);
print_r($data_array);
$array_length = count($data_array);
echo $array_length;
while(count($data_array)){
echo "execution "; // This would be replaced by the SQL insert statement
}
you should use
foreach($data_array as $array)
{
//sql
}
When you access the submitted data in your php, it will be available in either $_GET or $_POST arrays, depending upon the method(GET/POST) in which you have submitted it. Avoid using the $_REQUEST array. Instead use, $_GET / $_POST (depending upon the method used).
To loop through each element in an array, you could use a foreach loop.
Example:
//...
foreach($data_array as $d)
{
// now $d will contain the array element
echo $d; // use $d to insert it into the db or do something
}
Use foreach for the array or decrement the count, your while loop
is a infinite loop if count is >0
I seem to have looked everywhere for this.
Here is the code i use to set a variable to a piece of data from a MySQL database
$PartNo=mysql_result($result,$i,"PartNo");
Where
$result = mysql_query("SELECT * FROM PriceList");
$i = 0, is added to by 1 every time my while loop restarts
PartNo is a field name in my MySQL table and also the name of the variable I want to set the data in the database to
PriceList is my database name
I want to loop through all the field names (the array has them) and set variables with the same names to that data. Like this:
$PartNo=mysql_result($result,$i,"PartNo");
$Group=mysql_result($result,$i,"Group");
$OnHand=mysql_result($result,$i,"OnHand");
$QOO=mysql_result($result,$i,"QOO");
$Description=mysql_result($result,$i,"Desc");
$Cost=mysql_result($result,$i,"Cost");
But with a foreach loop so it isn't as much code.
I was thinking something like this, but it won't execute no matter which way I go about it (parse_str, eval, exec, etc.)
$nDatabaseVars=array("PartNo","Group","OnHand","QOO","Desc","Cost");
foreach ($nDatabaseVars as $X) {
$$X=mysql_result($result,$i,'$X');
}
I need "$$X" to evaluate out so on the first iteration, it changes to $PartNo= and then sets $PartNo to whatever data is in the database on the first line. Which is what this part is: mysql_result($result,$i,"PartNo")
If I echo it out instead:
foreach ($nDatabaseVars as $X) {
echo "$$X=mysql_result($result,$i,'$X')";
}
I can get it to say exactly what I need executed ($PartNo=mysql_result($result,$i,"PartNo");) but not actually get the variable set.
You are passing a string containing "$X" to mysql_result, not the name of your column. Remove the single quotes:
$$X=mysql_result($result, $i, $X);
$$X=mysql_result($result,$i,'$X'); // these single quotes around $X avoid your actual string to be used.
$$X=mysql_result($result,$i,"$X");