How to count multiple variables with strlen - php

I am looking to count the length of strings in multiple variables and add them together to get the total count.
I have tried strlen but have either messed up the syntax or have not used the proper code.
//$_SESSION['var1'] and $_SESSION['var2'] will each be numbers from -30.0 to 1000.0. I need the lengths of the two variables to be added. I need the negative sign(s) and decimal separators, or dots, to be counted.
$_SESSION['var_array'] = $_SESSION['var1'].$_SESSION['var2'];
$_SESSION['var_count'] = strlen($_SESSION['var_array']);
or
$_SESSION['var_count'] = strlen($_SESSION['var1'])+strlen($_SESSION['var2']);
Various results are observed. Sometimes the correct number IS observed but usually not.

The problem is that just storing numeric values doesn't maintain trailing decimals if they are 0. You could alternatively store them as strings, which will maintain the values exactly as you want them or format the numbers to ensure they contain the right format. The following code shows what I mean...
$_SESSION['var1'] = -30.0;
echo $_SESSION['var1'].PHP_EOL; // Gives -30
$_SESSION['var1'] = number_format($_SESSION['var1'], 1);
echo $_SESSION['var1'].PHP_EOL; // gives -30.0
$_SESSION['var2'] = "1000.0";
echo $_SESSION['var1'].PHP_EOL; // gives 1000.0
$_SESSION['var_array'] = $_SESSION['var1'].$_SESSION['var2'];
echo strlen($_SESSION['var_array']); // gives 11

Related

calculate with decimal values

At the the moment, I stored values in my mysql database as a decimal value (199,54).
But If I get this value with php (mysql query) and would like to calculate with it:
echo ($row->myValue) / 5;
I get the error:
A non well formed numeric value encountered ...
Where is my mistake?
You can use floatval function to convert decimal value that is fetched from database and then you can use in calculation:
$floatValue = floatval($row->myValue);
Now you can use $floatValue variable in any calculation.
As others have pointed out decimal separator in php is dot (.) not comma (,).
Either change the separator on the DB level to . or run the following anytime you want to deal with numbers stored in the database. First two lines are just an example to get it running locally for me
<?php
$row = new stdClass();
$row->myValue = "15,29";
$myValue = str_replace(',', '.', $row->myValue) / 5;
echo $myValue;
?>

Integer value ignoring zeros and returning full number

I'm looking to create a PHP Range loop
In a first and second number in the range, but have noticed the first number which is
00006
Is being rounded down / flattened to show "6".
So when I echo the first number value I get "6" back. I need it to be "00006"
Then the next number will need to be 00007 and so on, via the range loop.
My PHP code at present is :
$first_number = 00006;
$last_number = 11807;
foreach(range($first_number, $last_number) as $id)
{
echo $id;
}
How do I go about making sure that the number has the previous 0's in it?
You can do it by using printf() function.
See the documentation : printf
First of all in PHP, a number starting with zero is treated as octal number, But I guess range() function converts it as decimal. So if you want to start it with 20. Like $first_number = 00020; then the output will be start with 16 not 20.
So, if you want the output starting with 0's, then you can do like this:
$first_number = 6;
$last_number = 11807;
foreach(range($first_number, $last_number) as $id)
{
printf("%05d",$id);
}

Format number as currency

I am (learning) using PHP to select column data from MySQL into an array using this, CONCAT('$',FORMAT(price, '5')) as price and it outputs $1,751.60000 or $10.00230 or $7.23000 which is great.
However, I would like to remove the trailing zeros but still be able to have a minimum of two decimal places
$1,751.60000 = $1,751.60
$10.00230 = $10.0023
$7.23000 = $7.23
I have read a number of similar post regarding number to currency conversion but none doesn't seem to solve my problem as they remove all the trailing zeros.
We will implement this in two way.(Mysql, PHP).
MYSQL:
FORMAT('price', 2 ) This is mysql function. It takes first parameter as value & second parameter is the number of decimal places.
Syntax:
FORMAT( value, Decimal );
Example:
FORMAT('1751.60000', 2 ) => 1751.60 // Output
FORMAT('1751.60000', 3 ) => 1751.600 // Output
PHP:
In PHP we have number_format() function. This is working same as MYSQL.
Syntax:
number_format( value, Decimal );
Example:
number_format('1751.60000', 2 ) => 1751.60 // Output
number_format('1751.60000', 3 ) => 1751.600 // Output
The Best way is to implement at MYSQL.
Note: These both function round up the values.
I will post this code in PHP since it is easier for me.
$price = $row['price']; // the original price
if (number_format($price, 2) == $price) {
echo '$'.number_format($price, 2);
} else {
echo '$'.rtrim(number_format($price, 5),'0');
}
rtrim will remove any trailing character specified. In this case, remove trailing zeros.
Note : I only put this code number_format($price, 5) because of the sample of the question. If you wish to keep all decimal number minus trailing zeros, just using $price is enough.

How to calculate using a POST variable?

I need to multiply this POST variable by 12. As an example, if the amount was 10, the result should say:
Amount: 120
Here's my code so far:
Amount :'.$_POST['my_amount'].'<br/>
I tried to run the calculation in another variable, but this doesn't seem to work:
$result = ($_POST['my_amount'])*12;
or maybe it works and my output code is not working:
$vl_text='';
Amount :'.$_POST['my_amount'].'<br/>'.;
If you want your output to resemble your first example.,.. Amount:120 your missing chunks in each of the following 3 examples. first ensure that your $_POST variable is a valid one and set it to a new variable so you can print out the variable if you need to ...
// if you only expect $_POST['my_amount'] to contain integers...
if(is_int(intval($_POST['my_amount']))){
$my_amount = intval($_POST['my_amount']) * 12;
// or if you expect $_POST['my_amount'] to possibly contain a decimal
if(is_float(floatval($_POST['my_amount']))){
$my_amount = floatval($_POST['my_amount']) * 12;
intval ensures that a variable is cast as an integer if it can be, while not entirely necessary as multiplying in php will do this...its good practice to check any variables that you are using for and math functionality.
floatval does the same for for numbers with decimal. as an integer has to be a whole number if your variable could numbers that could contain decimals... use floatval
all of your examples then need to specify to print/echo the string....so
// your second line
echo 'Amount :'.$my_amount .'<br/>';
// your fourth line...
$vl_text='Amount: '.$my_amount;
echo $vl_text;
}
The most logical explanation is that you get string from POST. A good way to achieve what you want is to convert the POST value to int but keep in mind that it could not be numerical.
$int = (is_numeric($_POST['my_amount']) ? (int)$_POST['my_amount'] : 0); //If POST value is numeric then convert to int. If it's not numeric then convert it to 0
$_POST['my_amount'] = 150;
$data = $_POST['my_amount'] * 12;
echo $data;
Result will be 1800

PHP not dividing correctly

I have some PHP code that is dividing two numbers that are pulled from a mySQL database however it is not computing correctly. When I echo $comm and $total_fix individually, the numbers are correct. However, when I echo the division of the two it is not the correct answer. Both numbers are DECIMAL(10,0) data type in the database. Below is the PHP code
$percent_comm = $comm / $total_fix;
$percent_comm = number_format($percent_comm, 2, '.', ',');
echo "<td align=\"center\">".$percent_comm."</td>";
here $comm = 2700, $total_fix = 75 but $percent_comm is computing to be 0.03 when it should be 36
From what I see on your comments, you are getting the $comm variable as a string with a comma, because of the format. I suggest to convert the formatted string into a valid number.
Mean while I'll recomend this:
$comm = '2,700';
$comm = str_replace(',','',$comm);
That remove the comma from your number.
From the variable names, you want to know $comm as a percentage of $total_fix. Your code almost does this: You correctly divide $comm/$total_fix, and it correctly gives you 0.027. But you got it backwards when you checked by hand: 36 is the result of dividing 2700/75 (i.e., $total_fix/$comm)
But to get a percentage, multiply by 100 the result of the division:
(75.0 / 2700) * 100 = 2.7 percent.
That's what your code should be getting.

Categories