<?php
session_start();
if(isset($_SESSION['enter']))
$_SESSION['enter']=$_SESSION['enter']+1;
else
$_SESSION['enter']=1;
if ($_SESSION['enter']=7) {
unset($_SESSION['enter']);
$_SESSION['enter']=1; // here I want to count from beginning if there are seven enters
}
$enter = $_SESSION['enter'];
$enter = sprintf("%03d", $enter);
echo $enter; //keep always 001
?>
So, I want to count page enters from 1 to 7 and then back to 1... and so on, but in the above case it always stays on 1.
Any help.
if ($_SESSION['enter']=7) {
==, not =
This is your problem:
if ($_SESSION['enter']=7) {
You are not comparing the values, but assigning it and that always returns a true value, causing the code after it to run.
Just change it to:
if ($_SESSION['enter']===7) {
In this case you can also skip the if and do:
$_SESSION['enter'] = ($_SESSION['enter'] % 7) + 1;
in your first if statement. More about the modulus operator.
Related
I'm trying on PHP 7.4
<?php
function test(){
do{
$val=(int)readline("Insert a number in the range of 1-5 :");
print_r(($val>5 || $val!==0)."\n");
}while ($val>5 || $val!==0);
}
test();
But it just doesn't work as expected. It just leaves the loop when I insert 0, but not when I insert a number less than or equal to 5.
This condition is incorrect for what you're trying to do.
while ($val>5 || $val!==0)
None of the numbers you want to cause the loop to end are equal to zero, so the $val!==0 part of the condition will always be true unless $val is zero.
If either part of an or expression like $val>5 || $val!==0 is true, then the entire expression is true.
You need this instead:
while ($val > 5 || $val < 1)
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.
I have weird problem with data handling. I need to pick data from the user form, and handle it (generate xml).
The data is for example this:
2000;AC;1;60;5;5;Do your setup - meaning voltage, voltage type, test current, test time, ramp-up time, rampdown time, and user prompt.
I want to decide how to assemble my xml file based on the last value. If it is zero, there will be shorter xml assembly, while when there is text, there will be user prompt assembly of xml taggery.
So I explode the input into array, and check the value by:
If (empty($xplodline[6]) == true) {do this;}
else {do that;}
The problem is, that it always only does "that", and never "this", even when there is 0 in the $xplodline[6] as intended.
So I put echo $xplodline[6]; into {do that;} to see what´s happening.
The zero is echoed, (and while this action is in the cycle, I get other $xplodline[6]s from the cycle), and I see there is a space between the zero in the $xplodline[6] and next $xplodline[6] iteration. When I look into user form or temporary cleaned file with these values, there is no space between. Where could it come from?
When I put another array divider into the user form to make it ;0; there is no space, and If statement works well.
Here is the original data from the temporary cleaned file:
2000;AC;1;60;5;5;0
2000;AC;1;60;5;5;Set your cables for X10
2000;AC;1;60;5;5;Set your cables for X10
Any idea?
Ok, here is the code:
$stringer = fopen($tempfile, "r");
while(!feof($stringer)){
$oneline = fgets($stringer) ;
$xplodline = explode(";",$oneline) ;
$range01 = "gross" ;
$rampup = "100" ;
$rampdown = "100" ;
$rampupfunction = "false" ;
$rampdownfunction = "false" ;
$currentrange = "_1mA" ;
$assy01 = "1" ;
if ($xplodline[0] >= 3000) {$range01 = "gross" ;}
else {$range01 = "klein" ;}
if (empty($xplodline[4]) == false) {$rampupfunction = "true" ; $rampup = round($xplodline[0] / $xplodline[4]) ;}
if (empty($xplodline[5]) == false) {$rampdownfunction = "true" ;$rampdown = round($xplodline[0] / $xplodline[5]) ;}
if ($xplodline[2] < 1) {$currentrange = "_1mA";}
if ($xplodline[2] >= 1 && $xplodline[2] < 10) {$currentrange = "_10mA";}
if ($xplodline[2] >= 10 && $xplodline[2] < 100) {$currentrange = "_100mA";}
if (empty($xplodline[6]) == true) {$assy01 = $xmltestbegin.$xplodline[0]."V ".$xplodline[1].$xmltype.$xplodline[1].$xmlrange.$range01.$xmlrampup.$rampupfunction.$xmlrampdown.$rampdownfunction.$xmlcurrentrange.$currentrange.$xmlvoltage.$xplodline[0].$xmlrampupspeed.$rampup.$xmlrampdownspeed.$rampdown.$xmltesttime.$xplodline[3].$xmlcurrent.$xplodline[2].$xmlballast ;}
else {$assy01 = $xmlpromptbegin.$xplodline[6].$xmlpromptend.$xmltestbegin.$xplodline[0]."V ".$xplodline[1].$xmltype.$xplodline[1].$xmlrange.$range01.$xmlrampup.$rampupfunction.$xmlrampdown.$rampdownfunction.$xmlcurrentrange.$currentrange.$xmlvoltage.$xplodline[0].$xmlrampupspeed.$rampup.$xmlrampdownspeed.$rampdown.$xmltesttime.$xplodline[3].$xmlcurrent.$xplodline[2].$xmlballast ;}
file_put_contents ( $filename, $assy01, FILE_APPEND );
}
fclose($stringer);
My function works ok, every If except the last one, works...
From http://php.net/manual/en/function.fgets.php
Reading ends when length - 1 bytes have been read, or a newline (which is included in the return value), or an EOF (whichever comes first). If no length is specified, it will keep reading from the stream until it reaches the end of the line.
In short, there's always going to be a newline character in your last array entry. Clean it up by doing
$oneline = rtrim(fgets($stringer));
You can also consider:
$stringer = fopen($tempfile, "r");
while(!feof($stringer)){
$xplodline = fgetcsv($stringer,0,";");
//Rest of code as normal
which would let PHP handle the file as a CSV style file.
I have two variables in a PHP program for billing statements, $charges and $payments.
$charges is the total amount due before any payments. $payments is the total amount received.
I calculate the balance due like so:
$balance_due = $charges-$payments;
Simple, except I am getting the following result:
$balance_due has -9.0949470177293E-13 for a value (expecting 0).
Both $charges and $payments have a value of 5511.53.
When I var_dump($charges) and var_dump($payments) they both show: float(5511.53)
This code (and === ):
if($charges == $payments){
error_log('they are the same');
}else{
error_log('they are not the same');
}
both result in false.
If I hard code: $charges = $payments = 5511.53; and run it then $balance_due = 0 as expected.
I am confused. What am I missing?
EDIT NOTES
I was able to use a user contributed function by Nitrogen found on the BC Math Functions page that was suggested I look at in order to come up with the following solution:
if(Comp($charges, $payments)===0){
$balance_due = 0;
}else{
$balance_due = ( $charges - $payments );
}
function Comp($Num1,$Num2,$Scale=null) {
// check if they're valid positive numbers, extract the whole numbers and decimals
if(!preg_match("/^\+?(\d+)(\.\d+)?$/",$Num1,$Tmp1)||
!preg_match("/^\+?(\d+)(\.\d+)?$/",$Num2,$Tmp2)) return('0');
// remove leading zeroes from whole numbers
$Num1=ltrim($Tmp1[1],'0');
$Num2=ltrim($Tmp2[1],'0');
// first, we can just check the lengths of the numbers, this can help save processing time
// if $Num1 is longer than $Num2, return 1.. vice versa with the next step.
if(strlen($Num1)>strlen($Num2)) return(1);
else {
if(strlen($Num1)<strlen($Num2)) return(-1);
// if the two numbers are of equal length, we check digit-by-digit
else {
// remove ending zeroes from decimals and remove point
$Dec1=isset($Tmp1[2])?rtrim(substr($Tmp1[2],1),'0'):'';
$Dec2=isset($Tmp2[2])?rtrim(substr($Tmp2[2],1),'0'):'';
// if the user defined $Scale, then make sure we use that only
if($Scale!=null) {
$Dec1=substr($Dec1,0,$Scale);
$Dec2=substr($Dec2,0,$Scale);
}
// calculate the longest length of decimals
$DLen=max(strlen($Dec1),strlen($Dec2));
// append the padded decimals onto the end of the whole numbers
$Num1.=str_pad($Dec1,$DLen,'0');
$Num2.=str_pad($Dec2,$DLen,'0');
// check digit-by-digit, if they have a difference, return 1 or -1 (greater/lower than)
for($i=0;$i<strlen($Num1);$i++) {
if((int)$Num1{$i}>(int)$Num2{$i}) return(1);
else
if((int)$Num1{$i}<(int)$Num2{$i}) return(-1);
}
// if the two numbers have no difference (they're the same).. return 0
return(0);
}
}
}
That solution worked for me. The answer provided by imtheman below also works and seems more efficient so I am going to use that one instead. Is there any reason not to use one or the other of these?
The way I solved this problem when I ran into it was using php's number_format(). From php documentation:
string number_format(float $number [, int $decimals = 0 ])
So what I would do is this:
$balance_due = number_format($charges-$payments, 2);
And that should solve your problem.
Note: number_format() will return a string, so to compare it you must use == (not ===) or cast it back into a (float) before comparison.
I am trying to create a hit counter that once it reaches a certain number (in this case, 5), it will no longer display the amount of hits. This is my code:
<?php
$count = ("hits.txt");
$hits = file($count);
$hits[0] ++;
$fp = fopen($count , "w");
fputs($fp , "$hits[0]");
fclose($fp);
if ($hits > 5) {
echo "More than 5 hits";
}
else {
echo $hits[0];
}
?>
What am I doing wrong?
You are overcomplicating things. It would be much easier to do it like this:
$hits = file_get_contents('hits.txt');
++$hits;
file_put_contents('hits.txt', $hits);
if($hits > 5) {
echo 'Over 5!';
}
// else etc
As for your current code, the problem is that you don't test the number of hits with the correct syntax $hits[0] -- which you already use in fputs -- but with the wrong $hits instead. Remember that due to the way file works, $hits itself is an array. PHP will happily let you compare an array to an integer, and there are rules that define how the comparison works, but don't go there.
You need $hits[0] > 5:
if ($hits[0] > 5) {
echo "More than 5 hits";
}
The array value $hits when compared against a number 5 is compared as the string Array rather than the value of the array's first item. The string Array is always greater than 5.
More or less everything. In addition to other answers this
fputs($fp , "$hits[0]");
won't work as expected, you want either "{$hits[0]}" or $hits[0] (no quotes).
That is, if you don't care about concurrent access.