How do I use functions in my php code? [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm learning about functions in my programming class and no matter what I do I just cant get this to work. Here is the problem that needs fixing:
What's wrong here?
The getWage() function is supposed to calculate overtime (time and a half) for any hours worked above 40. The function is working just fine but when we send the $hoursWorked and $hourlyWage from THIS program the function does not calculate the overtime as time and a half!
Can you fix it? The wage should be $605.63 not $573.75
Here is my function:
<?php
function getWage($hourlyWage, $hoursWorked) {
if ($hoursWorked <= 40)
return round(($hourlyWage * $hoursWorked), 2);
else
return round((($hourlyWage * 40) +
($hourlyWage * 1.5 * ($hoursWorked - 40))), 2);
}
?>
and here is where I try to call it to my program:
<?php
include("incWageFunctions.php");
$hourlyWage = 12.75;
$hoursWorked = 45;
$wage = getWage($hoursWorked, $hourlyWage);
print("<p>Your hourly wage is $$hourlyWage and you worked
$hoursWorked hours.</p>");
print("<p>Your wages are $$wage.</p>");
?>
Its not calculating the overtime no matter what... Where am I going wrong?! Also, how would you call multiple functions to the same program to calculate different things? Can I just call it with the name after the include statement? Or do I have to have it written out with the { } like my first function in this question??

You interchanged $hoursWorked and $hourlyWage
Change $wage = getWage($hoursWorked, $hourlyWage);
To $wage = getWage($hourlyWage, $hoursWorked);

You have mixed up the arguments. In php-file you have coded:
$wage = getWage($hoursWorked, $hourlyWage);
However, in incWageFunctions.php you have written:
function getWage($hourlyWage, $hoursWorked)

Related

How can i make a generated code using fpdf [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
This code was made by other, but i want to change it for my own purposes.
The code is giving 13 numbers, but only want the numbers of the ID(from database).
Example of what i need:
ID = 908
EAN13 = 000000908
My real question is how can i remove the 0000 from the BARS, then after scanning the SCANNER wil read the correct ID.
This is fora study guys!
class PDF_BARCODE extends FPDF
{
function EAN13($x, $y, $barcode, $h=16, $w=.35, $fSize=9)
{
$this->Barcode($x,$y,$barcode,$h,$w,$fSize,13);
}
function UPC_A($x, $y, $barcode, $h=16, $w=.35, $fSize=9)
{
$this->Barcode($x,$y,$barcode,$h,$w,$fSize,12);
}
function GetCheckDigit($barcode)
{
//Compute the check digit
$sum=0;
for($i=1;$i<=11;$i+=2)
$sum+=3*$barcode[$i];
for($i=0;$i<=10;$i+=2)
$sum+=$barcode[$i];
$r=$sum%10;
if($r>0)
$r=10-$r;
return $r;
}
function TestCheckDigit($barcode)
{
//Test validity of check digit
$sum=0;
for($i=1;$i<=11;$i+=2)
$sum+=3*$barcode[$i];
for($i=0;$i<=10;$i+=2)
$sum+=$barcode[$i];
return ($sum+$barcode[12])%10==0;
}
function Barcode($x, $y, $barcode, $h, $w, $fSize, $len)
{
//Padding
$barcode=str_pad($barcode,$len-1,'0',STR_PAD_LEFT);
if($len==12)
$barcode='0'.$barcode;
//Add or control the check digit
if(strlen($barcode)==12)
$barcode.=$this->GetCheckDigit($barcode);
elseif(!$this->TestCheckDigit($barcode))
$this->Error('Incorrect check digit');
//Convert digits to bars
$codes=array(
'A'=>array(
'0'=>'0001101','1'=>'0011001','2'=>'0010011','3'=>'0111101','4'=>'0100011',
'5'=>'0110001','6'=>'0101111','7'=>'0111011','8'=>'0110111','9'=>'0001011'),
'B'=>array(
'0'=>'0100111','1'=>'0110011','2'=>'0011011','3'=>'0100001','4'=>'0011101',
'5'=>'0111001','6'=>'0000101','7'=>'0010001','8'=>'0001001','9'=>'0010111'),
'C'=>array(
'0'=>'1110010','1'=>'1100110','2'=>'1101100','3'=>'1000010','4'=>'1011100',
'5'=>'1001110','6'=>'1010000','7'=>'1000100','8'=>'1001000','9'=>'1110100')
);
$parities=array(
'0'=>array('A','A','A','A','A','A'),
'1'=>array('A','A','B','A','B','B'),
'2'=>array('A','A','B','B','A','B'),
'3'=>array('A','A','B','B','B','A'),
'4'=>array('A','B','A','A','B','B'),
'5'=>array('A','B','B','A','A','B'),
'6'=>array('A','B','B','B','A','A'),
'7'=>array('A','B','A','B','A','B'),
'8'=>array('A','B','A','B','B','A'),
'9'=>array('A','B','B','A','B','A')
);
$code='101';
$p=$parities[$barcode[0]];
for($i=1;$i<=6;$i++)
$code.=$codes[$p[$i-1]][$barcode[$i]];
$code.='01010';
for($i=7;$i<=12;$i++)
$code.=$codes['C'][$barcode[$i]];
$code.='101';
//Draw bars
for($i=0;$i<strlen($code);$i++)
{
if($code[$i]=='1')
$this->Rect($x+$i*$w,$y,$w,$h,'F');
}
//Print text uder barcode
$this->SetFont('Arial','',$fSize);
$this->Text($x,$y+$h+11/$this->k,substr($barcode,-$len));
}
}
The EAN-13 barcode format inherently encodes 13 digits. If you mess with it so it encodes fewer digits, the barcode will no longer be EAN-13, and many barcode readers will not recognize it.
You're using leading zeros on your codes in your nonstandard application. I say nonstandard because EAN-13 has a registry of prefixes. Whatever you use to read your barcodes will need to remove the leading zeros.
If you must avoid leading zeros in your barcode, you may want to switch to another more flexible barcode format, Code 39, Codabar, or even QR codes. Or you might choose EAN-8 or EAN-5. You can look up all these.

PHP - if int reached to n [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Take these levels:
level1 = 0days
level2 = 30days
level3 = 90days
All these levels are totally dynamic. Admin can alter number of levels and duration of levels at any time.
I am recording numberOfDailyLogin in a series, so if user not login even for 1 day meter reset to 0.
I am trying to give user a special level tag on basis of numberOfDailyLogin
I have a solution already by running a while loop from 0 to numberOfDailyLogin and update variable once >= daysRequired for login.
But I don't want it this way, want something easy
I am totally clueless at this point, I can't hardcode any of the
value, so please if you are interest please give some suggestion.
#Edit1
// json response for levels
{
"status": 200,
"body": [
{
"name": "level1",
"after_days": 0,
},
{
"name": "level2",
"after_days": 50,
},
{
"name": "level3",
"after_days": 180,
}
]
}
function getLevel($allLevels, $numberOfDailyLogins) {
foreach ($allLevels as $l) {
if ($numberOfDailyLogins > $l['after_days']) {
return $l['name'];
}
}
}
Problem is if numberOfDailyLogins=51.. so it should show level2... cause after 50 days userLevel reached to level2.. but my code return level1 which is totally wrong.
#brombeer suggestion works for me, Thanks mate
function getLevel($allLevels, $numberOfDailyLogins) {
$level = null;
foreach ($allLevels as $l) {
if ($numberOfDailyLogins> $l['after_days']) {
$level = $l;
}
}
// TO-DO... do whatever you want
}
It's a simple logic error - your code returns after the first iteration because the value is already greater than 0 (the first level in the list).
One simple solution is to search the array in reverse instead:
function getLevel($allLevels, $numberOfDailyLogins) {
for ($i = count($allLevels) -1; $i >= 0; $i--) {
if ($numberOfDailyLogins > $allLevels[$i]['after_days']) {
return $allLevels[$i]['name'];
}
}
}
Demo: http://sandbox.onlinephpfunctions.com/code/3b00c6d182676411915cae1fbb21a1afba2548e8

I am wondering how can i rate limit my php api so a ip or client cant use it for 5 minutes [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
So, i have a super basic php api for my website and i need it to be rate limited.
Like a cooldown so the ip cant access the api for 5 minutes.
Thanks in advance =)
There's a couple ways you could do it, in order of preference....
Use a database; have a table which logs the ip and timestamp then lookup the ip on every request and check the time of the last request is more than 5 minutes ago
Use a file to store the request ip and timestamp in something like CSV or JSON format. Then loop over the file with each request...
Seeing as you don't say anything about access to a database, here is a version for a JSON formatted file:
Note: you need to update the $filePath variable
$ip = $_SERVER["REMOTE_ADDR"];
$filePath = "./path/to/file.json"; // Set this to a file on your server
$ipList = json_decode(file_get_contents($filePath), true);
$throttleTime = date("Y-m-d H:i:s", strtotime("-5 minutes");
$allowAccess = true;
foreach ($ipList as $key => $row) {
// Check if the IP has accessed the site in the last 5 minutes
if ($row["ip"] === $ip && $row["timestamp"] > $throttleTime)) {
$allowAccess = false;
}
// Remove the entry if over 5 minutes old; not restricted to IP
// >> Garbage colection
if ($row["timestamp"] < $throttleTime) {
unset($ipList[$key]);
}
}
$ipList[] = [
"ip" => $ip,
"timestamp" => date("Y-m-d H:i:s"),
];
// Update the
file_put_contents($filePath, json_encode(array_values($ipList)));
// Check to see if the user is allowed access; exit with error message if not.
if (!$allowAccess) {
echo "Error, you've accessed this site too many times. Try again in 5 minutes.";
exit;
}
// The user is allowed... Do something....
echo "We're in!";

How to find divergent coordinates? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a list of coordinates (longitude and latitude) in a csv-file. The coordinates are representing a store. There are almost a hundred files over stores, one per country. But some coordinates are wrong (Manually written in by employees).
There are about 100 stores (in average) in each country.
I could sent the coordinates to the google api to check if it is the same country as the rest but the google maps api will only recieved 2500 request for free.
How could I code a method that will just test some divergent coordinates instead of every coordinate?
Here we have a example of coordinates of stores in france. But one coordinate is located in Ghana.
latitude longitude
42,82377 0,316521
46,180742 6,7042473
45,0144927 6,1242264
42,6281 9,4206
46,0259861 6,6388244
47,9622395 1,8441825
5,623027 -1,043182
44.773491 6.03283
48,2814547 7,4579305
50.726231 1.60238
45,751175 3,110678
46,1875023  5.2071938
44,944816 4,841903
45,1484023 5,7223511
44,556944 4,749496
45,467654 4,352633
45,564601 5,917781
45,556935 5,971688
47,312494 5,117044
45,93813 6,090965
Maybe making an average value of coordinates :
$average = array('latitude' => 0, 'longitude' => 0);
// determine the total of coordinates values
foreach($coordinates as $coord){
$average['latitude'] += $coord['latitude'];
$average['longitude'] += $coord['longitude'];
}
// Divide by the number of coordinates to get an average value of the lat/long
$average['latitude'] /= count($coordinates);
$average['longitude'] /= count($coordinates);
// max distance to considere the measure is bad
$maxDistance = 5.0; // YOU SHOULD CONFIGURE THIS VARIABLE
// then, we determinate strangers :p
$strangers = array();
foreach($coordinates as $coord){
if($coord['latitude'] > $average['latitude'] + $maxDistance
OR $coord['latitude'] < $average['latitude'] - $maxDistance
OR $coord['longitude'] > $average['longitude'] + $maxDistance
OR $coord['longitude'] < $average['longitude'] - $maxDistance){
$strangers[] = $coord;
}
}
// you get your list, and you can use it
foreach($strangers as $strange){
echo $strange['latitude'] . " : " . $strange['longitude'];
}
I think there are many algorithmes outhere which are better than this one by the way...

Mongo faster than MongoClient [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Mongo::__construct is deprecated following php.net, and it's faster 3 times than MongoClient!!
Try it yourself, run the below code which insert 1M docuements, it will finish in ~20 sec the replace mongo with mongoClient which will finish in ~180 sec
<?php
function mongo_connect($db, $collection) {
$mongo = new Mongo( 'mongodb://localhost' );
return $mongo->$db->$collection;
}
$mongodb='notificator1';
$mongocollection='tok';
$collection= mongo_connect($mongodb, $mongocollection);
echo $time = microtime(true). "\n";
$i=0;
while ( $i < 1000000 ) {
$row = Array('title' => "test #$i");
$collection->save($row);
++$i;
}
echo microtime(true) - $time;
?>
replace mongo_connect:
function mongo_connect($db, $collection) {
$m = new MongoClient('mongodb://localhost:27017');
$db = $m->selectDB($db);
return $collection = new MongoCollection($db, $collection);
}
Mongo is faster but that IS NOT A GOOD THING.
But the answer to your actual question is in the code:
$mongo = new Mongo( 'mongodb://localhost' );
The default write concern of Mongo is 0 which means it won't bother to check if the write actually worked whereas MongoClient will.
Here is a good post that explains the differences between Mongo and MongoClient form one of the mantainers of PHP and the MongoDB Driver: http://derickrethans.nl/mongoclient.html .
Now, you may be wondering why we are replacing Mongo with MongoClient across the board. The biggest reason is that the new class will have acknowledged writes on by default

Categories