John Davidson

How to sum up value in session - PHP

0 comments
Message:


I'm trying to sum up all the values returned from a session but I'm unable to achieve this with array_sum(); but return nothing. Below is what my code looks like:


<?php 

for($i=0;$i<count($_SESSION['img_src']);$i++){

$subTotal = $_SESSION['price'][$i];
echo $subTotal;

}

?>

In the above code echo $subTotal; returns 9,999 11,999 9,999 and I tried using echo array_sum($subTotal); but got nothing and I want to be able to get a sum up to be 31,997



My Answer:
You can sum up the values stored in a session by first retrieving the values from the session and then using a loop to calculate the sum. Here is an example code snippet that demonstrates how to achieve this:

php
// Start the session
session_start();

// Check if the session variable is set
if(isset($_SESSION['values'])) {
// Retrieve the values from the session
$values = $_SESSION['values'];

// Initialize a variable to store the sum
$sum = 0;

// Loop through the values and calculate the sum
foreach($values as $value) {
$sum += $value;
}

// Output the sum
echo "The sum of the values in the session is: " . $sum;
} else {
echo "No values found in the session.";
}


Make sure to replace `$_SESSION['values']` with the actual session variable that stores the values you want to sum up. This code will calculate the sum of the values stored in the session and output the result.

Rate this post

5 of 5 based on 6056 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us