How to Echo a Sum of a Variable and a Number

How do I echo a sum of a variable and a number?

No need for expr, POSIX shell allows $(( )) for arithmetic evaluation:

echo $((x+1))

See §2.6.4

PHP - How to echo the sum of values in a column?

Try this,

$result = mysql_query('SELECT SUM(votes) AS value_sum FROM table_name'); 
$row = mysql_fetch_assoc($result);
$sum = $row['value_sum'];

With SQLi

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT SUM(votes) AS value_sum FROM table_name";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "sum is : " . $row["value_sum"];
}
} else {
echo "0 results";
}
$conn->close();

bash script to sum number of sum variable and display it with the topic name in a JSON

Try this script:

#!/bin/bash
temp=$(jq length sample.json)
len=$((temp-1))

x=0

while [ $x -le $len ]
do
partitions=$(jq ".brokers[${x}].logDirs[].partitions[]" sample.json)
part_size=$(jq ".brokers[${x}].logDirs[].partitions" sample.json)
total_size=$(echo $part_size | jq 'map(.size) | add')

echo "broker ${x}"
echo 'Topics Size'
echo $partitions | jq -r '"\(.partition)\t\(.size)"'
echo "total size ${total_size}"
printf "\n"

x=$(( $x + 1 ))
done

Replace sample.json file using your file.

shell script + numbers sum

How about:

num1=1232
num2=24
num3=444
sum=$((num1+num2+num3))
echo $sum # prints 1700

PHP - How to use the sum variable inside a loop

if you want the total sum of your $value inside the loop, you must first calculate it, before entering the loop:

$sum = array_sum(array_column($group, 'column_key'));

where 'column_key' is the index of the array $group containing the values you want to sum.

Example:

Let's say that we have this array containing values to sum:

$data = [
[
'id' => 2,
'name' => 'Jhon',
'salary' => 1500
],
[
'id' => 5,
'name' => 'Jane',
'salary' => 2000
]
];

Now we want the sum of all salaries:

$totSalary = array_sum(array_column($data, 'salary'));
// echo $totSalary will print 3500


Related Topics



Leave a reply



Submit