How to sum up values inside a array variable? - php

I have retrieved some values from database. In my view file I have the following:
$row['fee_amount'];
Now, I want to sum up all the values inside $row['fee_amount']; and then show it.
I know I could sum up when querying the database, but I am interested to learn how to add using PHP .
Would you please kindly teach me how to do it?
EDIT
<?php if(count($records) > 0) { ?>
<table id="table1" class="gtable sortable">
<thead>
<tr>
<th>S.N</th>
<th>Fee Type</th>
<th>Fee Amount</th>
</tr>
</thead>
<tbody>
<?php $i = 0; foreach ($records as $row){ $i++; ?>
<tr>
<td><?php echo $i; ?>.</td>
<td><?php echo $row['fee_type'];?></td>
<td><?php echo $row['fee_amount'];?></td>
</tr>
<?php } ?>
</tbody>
<tr>
<td></td>
<td>Total</td>
<td>
I WANT TO DISPLAY THE SUMMATION RESULT HERE ADDING UP VALUES INSIDE THIS>>> <? $row['fee_amount']; ?>
</td>
</tr>
</table>
<?php } ?>

In your view file, with your foreach loop, add a $sum variable next to your $i counter and add the amount per each iteration (similar to like you increase $i):
<?php
$i = 0;
$sum = 0;
foreach ($records as $row)
{
$i++;
$sum += $row['fee_amount']; ?>
(I put this over multiple lines to make it more readable).
After the foreach has finished, $sum contains the total amount:
<td>Total: <?php echo $sum; ?></td>
That simple it is. You only need a new variable ($sum) and do the calculation.

Use a loop
$sum = 0;
while($row...){
$sum += $row['fee_amount']
}
echo $sum;

You could use;
$someValue = 0;
foreach($row["fee_amount"] as $value) {
$someValue = $someValue + $value;
}

using this php function, if $row['fee_amount'] is an array ^_^
for example:
$a = array(2, 4, 6, 8);
array_sum($a)

Related

PHP totalling column and simplifying Sessions

I'm trying to total a column in a table of prices and it's not working out for me. I've looked at a ton of solutions such as array_sum() but it's not displaying anything for me. This is a cart page where I'm posting items to a session and then displaying in a for loop. I'm not sure if my sessions are overly complicated or what. Here is my session and post code:
session_start();
if( $_SERVER['REQUEST_METHOD'] == 'POST') {
$_SESSION['item'][] = array($_POST['item'], $_POST['price']);
}
?>
And here is my for loop section of code:
for($i=0; $i < count($_SESSION['item']); $i++){
$prices = $_SESSION['item'][$i][1];
$sum = 0;
$sum += $_SESSION['item'][$i][1];
print $sum;
?>
<tr>
<td class="left"> <?php print_r($_SESSION['item'][$i][0]) ?></td>
<td class="center"><?php echo "$ " . $_SESSION['item'][$i][1] ?></td>
</tr>
<?php
}
?>
<tr>
<td class="center">Total:</td>
<td></td>
</tr>
<?php
}
?>
</table><br>
Any help would be greatly appreciated!
Replace your current forloop with the following:
You were assigning $sum=0; inside loop so every time loop executed, your $sum variable would be assigned to zero and hence you would lose its value.
Sidenote: You should consider printing sum outside of loop.
$sum = 0;
for($i=0; $i < count($_SESSION['item']); $i++){
$prices = $_SESSION['item'][$i][1];
$sum += $_SESSION['item'][$i][1];
print $sum;
?>
At first your code must be like this:
$sum = 0;
for($i=0; $i < count($_SESSION['item']); $i++){
$prices = $_SESSION['item'][$i][1];
$sum += $prices;
?>
<tr>
<td class="left"> <?php print_r($_SESSION['item'][$i][0]) ?></td>
<td class="center"><?php echo "$ " . $_SESSION['item'][$i][1] ?></td>
</tr>
<?php
}
?>
<tr>
<td class="center">Total: <?=$sum?></td>
<td></td>
</tr>
<?php
}
?>
</table><br>
And the second if you want to sum column of prices from database then you can use mysql SUM function
Reference for mysql SUM

How do I display the output of a "while loop" in a table?

I don't even have an idea of where to start for this. I need to display 100 numbers in a table and would like to use a while loop to do so. Is there a "shortcut" to doing this?
For a table you need some tags table, tr and td. The tr and td are in while loop and the value $i will print inside the td.
<table>
<?php
$i = 1;
while($i != 101){?>
<tr><td><?php echo $i++;?></td></tr>
<?php }?>
</table>
You can use while, for, foreach for your convenience, like below code
<table>
<thead>
<tr>
<th class="header">Number</th>
</tr>
</thead>
<tbody>
<?php
$i = 1;
while($i != 101){
?>
<tr>
<td><?php echo $i; ?></td>
</tr>
<?php
$i++;
} ?>
</tbody>
</table>
You can dipslay 100 numbers simply in tbale like this:
<?php
// Using For loop
echo "<table>";
for ($i = 1;$i <= 100; $i++) { // use for loop
echo "<tr><td>".$i."</td></tr>";
}
echo "</table>";
// OR
// Using while loop
$i = 1;
echo "<table>";
while($i <= 100) {
echo "<tr><td>".$i."</td></tr>";
$i++;
}
echo "</table>";
?>
You can use a while loop:
while ($i <= 100) {
echo "<td><tr>" . $i++ . "</tr></td>";
}

For loop inside Foreach

I got a foreach which loops through my database for each user.
<?php
foreach($users as $user) {
?>
<tr>
<td>
<?php
for ($i=1; $i < 52; $i++) {
echo $i;
}
?>
</td>
<td>
<?php echo $user['firstname']; ?>
</td>
</tr>
<?php
}
?>
This loop through database and echos the username, now I tried to build a for loop inside this so that every user has a number, I took as an example a very basic for loop ( it will be changed later).
The problem is that I get all numbers printed out for each user, but I just want to print out the number once for a user. How do I solve this.
If you want unique index number for user, you do not need extra loop.
Just add an increment variable:
And increment it in existing loop.
<?php
$i=0;
foreach($users as $user) {
++$i; // For printing first user, it will be 1 not 0.
// Therefore, increment is placed before printing name.
?>
<tr>
<td><?php echo $i;?></td>
<td><?php echo $user['firstname']; ?></td>
</tr>
<?php
}
?>
This should be enough to achieve what you're trying to do :
Your for() isn't needed since foreach() already create a loop, you just have to use this loop to increment a value (here called $i) then display it.
Also you should avoid to open your php tags ten thousands times for a better visibility into your code :)
<?php
$i = 0;
foreach($users as $user) {
$i++;
echo'<tr>
<td>'.$i.'</td>
<td>'.$user['firstname'].'</td>
</tr>';
?>
<?php
$i=1;
foreach($users as $user) {
?>
<tr>
<td>
<?php
echo $i++;
?>
</td>
<td>
<?php echo $user['firstname']; ?>
</td>
</tr>
<?php
}
?>
Try to use the key in foreach
<?php foreach ($users as $key => $user) : ?>
<tr>
<td><?php echo $key; ?></td>
<td><?php echo $user['firstname']; ?></td>
</tr>
<?php endforeach; ?>

multiply 2 values from different table using codeigniter and postgresql foreach()

Here's the code from my
Controller Page
public function table1(){
$this->load->model('test_model');
$data['value']= $this->test_model->getAlltable1();
$data['value2']= $this->test_model->getAlltable0();
$this->load->view('table1', $data);
}
Views Page
<table class="table">
<tbody>
<?php foreach ($value as $v){ ?>
<?php foreach ($value2 as $v2){ ?> //different table
<tr>
<td><?php echo $v->tech_voc?></td>
<td><?php echo ($v->tech_voc*$v2->tech_voc)?></td>
</tr>
<?php } ?>
<?php } ?>
The output is somewhat like this
1 .75
1 .75
1 .75
1 .75
What I want to display is something like this
1 .75
What happen here is that, instead it multiply once, it all multiply each row. And I think it is because I put foreach inside a foreach Please help me.
EDIT
Oh yeah, I already tried deleting the foreach value2
but it says v2 is undefined variable
HOPE it helps.
NEW EDIT:---------------------------------------
If you're trying to multiply where the keys are the same ($value[0]*$value2[0], $value[1]*$value2[1], etc) try this.
<?php
$col1_sum = 0;
$col2_sum = 0;
foreach ($value as $k => $v){ ?>
<tr>
<td><?php echo $v->tech_voc?></td>
<td><?php echo ($v->tech_voc*$value2[$k]->tech_voc)?></td>
<?php //update sums
$col1_sum += $v->tech_voc;
$col2_sum += ($v->tech_voc*$value2[$k]->tech_voc);
?>
</tr>
<?php } ?>
<!-- row with sums -->
<tr>
<td><?php echo $col1_sum?></td>
<td><?php echo $col2_sum?></td>
</tr>
Edited based on comments/chat to include a sum row.

PHP AND FOR LOOP

I am trying to use for loops to create a table which dynamically returns something like this: Note how the td content have been arranged
<table>
<tr>
<td>1</td>
<td>3</td>
<td>5</td>
<td>7</td>
<td>9</td>
</tr>
<tr>
<td>2</td>
<td>4</td>
<td>6</td>
<td>8</td>
<td>10</td>
</tr>
</table>
among What I have tried so far is
$row=2;
$col=20;
$x=0;
echo '<table>';
for($i=0;$i<$row;$i++){
echo '<tr>';
for($k=0;$k<$col;$k++)
{
echo '<td>'.echo $x+=1.'</td>';
}
echo '</tr>';
}
In this case I get something different and which is not what I want.
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
<td>10</td>
</tr>
</table>
Kindly someone help me map this.Thanks
<?php
# how high to count
$count = 10;
# how many rows in the table
$rows = 2;
# figure out how many columns
$columns = ceil($count/$rows);
# could also go the other way and declare there to be 5 columns and then
# divide to get the rows, but since you're counting down the columns,
# I thought this made more sense. Either way.
?><table><?php
for ($i=0; $i<$rows; ++$i) {
?><tr><?php
for ($j=0; $j<$columns; ++$j) {
# calculate which number to show in column $j of row $i. Each column adds
# $rows numbers to the total, while each row just adds one more. And we
# want to start at 1 instead of 0.
$n = $j * $rows + $i + 1;
?><td><?= $n ?></td><?php
}
?></tr><?php
}
?></table>
$total_count = 10;
$total_rows = 2;
$table = array();
//building table array
for($i=1;$i<=$total_count;$i++) {
$row = $i % $total_rows;
$row = $row == 0 ? $total_rows : $row;
$table[$row][] = $i;
}
//generate table based on array
echo "<table>";
for($row=1;$row<=$total_rows;$row++) {
echo "<tr>";
foreach($table[$row] as $cell) {
echo "<td>".$cell."</td>";
}
echo "</tr>";
}
echo "</table>";
This isnt as complicated as people are making it seem
Start the inner loop at whatever row you're currently on and add 2 each time.
<?php
$rows=2;
$cols=10;
?>
<table>
<?php for($i=1;$i<=$rows;$i++): ?>
<tr>
<?php for($k=$i;$k<$cols;$k+=2): ?>
<td><?php echo $k ?></td>
<?php endfor; ?>
</tr>
<?php endfor; ?>
</table>
Id probably use range and foreach though
<?php
$rows=2;
$cols=10;
?>
<table>
<?php foreach( range( 1, $rows ) as $row ): ?>
<tr>
<?php foreach( range( $row, $cols, 2 ) as $col ): ?>
<td><?php echo $col ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>
This approach will split the data itself
function array_chunk_vertical($array = null,$cols = 3, $pad = array(null))
{
if (is_array($array) == true and !empty($array))
{
$rows = ceil(count($array)/$cols);
$array = array_chunk($array,$rows);
if (count($array) < $cols)
{
$array = array_pad($array,$cols,$pad);
}
foreach($array as $key => $value)
{
$array[$key] = array_pad($value,$rows,null);
}
foreach($array as $key => $value)
{
foreach($value as $sub_key => $sub_value)
{
$output[$sub_key][$key] = $sub_value;
}
}
return $output;
}
return $array;
}
$data = array(1,2,3,4,5,6,7,8,9,10,11);
echo '<table border="1">';
foreach(array_chunk_vertical($data,ceil(count($data)/2)) as $row)
{
echo '<tr>';
foreach($row as $col)
{
echo '<td>' . $col . '</td>';
}
echo '</tr>';
}
echo '</table>';

Categories