adding string and number together in php (FAULT!!) - php

I'm having little trouble with this code that reads ordernumbers from txt file, then adds 1 to that number. However PHP does not add these numbers together regardless of automatic type-casting...
$handle1 = fopen("ordernumbers.txt", "r");
$numberoforders = fgets($handle1);
$numberoforders = trim($numberoforders);
$orderid=$numberoforders+1;
echo $orderid;
When echoing $numberoforders, it returns number 5 (type is string)
When echoing $orderid, it returns 1, while it should give 6.
I can not see any problem here, and it still does not work. I tried also to change that variable type from string to int, and then add these numbers together, but same result (1).
edit:here's the contents of the txt file:
http://imgur.com/bzjOuOJ

As your var_dump gives string(4) ''5'' to string stored in $numberoforders must contain three more characters.
I suspect a linebreak or something similar

Because $numberoforders is converted into integer and its value is 0, so 0 + 1 =1 that's the output you are getting . If you want the string's characters number add to the integer value, you need to count the string's length first.
You can get your result like so
$handle1 = fopen("ordernumbers.txt", "r");
$numberoforders = fgets($handle1);
$numberoforders = trim($numberoforders);
$numberoforders = strlen($numberoforders);
$orderid=$numberoforders+1;
echo $orderid;

Related

How to count multiple variables with strlen

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

Increment by one value is not work while using large length of digit?

Currently i am tried to increment value by one but is not working while taking large length of digit.
For example..
Right now st_id is store in database like G4KZ00000001 now what i want when it's called second time then value will be increment by 1 so it would be then G4KZ00000002, G4KZ00000003 etc..
Following is my code..
Value get from DB..
$lastStconId =$last_api_record['st_consignment_id'];
Then Use following condition
if(empty($lastStconId)) {
$consignment_no = 'G4KZ00000001';
}else
{
$dataid = $last_api_record['st_consignment_id'];
$con = str_replace("G4KZ", "", $dataid);
echo $consignment_no = $con+1; // dynamic
echo $consignment_no = 'G4KZ'.$consignment_no;
}
When i print $consignment_no it's always return increment value but i want it with full string G4KZ00000002.
The problem is that when you increment $consignment_no with '00000001' you are getting 2 as this is a numeric value. To make it back to the full length you need to pad it out with zeros to the length of the original number. I use str_pad() with left padding with 0...
$consignment_no = 'G4KZ'.str_pad($consignment_no, strlen($con), "0", STR_PAD_LEFT);
You don't need to remove and re-add the G4KZ prefix at all - you can increment strings just fine in PHP. This also avoids the issue you're having with the padding being removed, since it treats the entire string as the operand.
$str = 'G4KZ00000001';
echo ++$str;
G4KZ00000002
See https://3v4l.org/nE8X9 for a demo with a few more iterations.

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

Use numbers starting with 0 in a variable in php

Hi i need to save a 010 number in $number and if i do like this php will remove the starting 0
$number = 010
And echo of this will return 10 how can i make it not to remove the initial 0
BR
Martin
Use it as a String:
$number = '010';
Use str_pad() function.
echo str_pad('10',3,'0',STR_PAD_LEFT)
http://php.net/manual/en/function.str-pad.php
Do remember that numbers starting with 0 can also be treated as octal number notation by the PHP compiler, hence if you want to work with decimal numbers, simply use:
$num = '010';
This way the number is saved, can be stored in the database and manipulated like any other number. (Thx to the fact that PHP is very loosely typed language.)
Another method to use would be:
Save number as $num = 10;
Later while printing the value you can use sprintf, like:
sprintf("%03d", $i);
This will print your number in 3 digit format, hence 0 will be added automatically.
Another method:
<?php
$num = 10;
$zerofill = 3;
echo str_pad($num, $zerofill, "0", STR_PAD_LEFT);
/* Returns the wanted result of '010' */
?>
You can have a look at the various options available to you and make a decision. Each of the method given above will give you a correct output.

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