Jump to content

Finding percentage difference to assign as $discount !


Steve1957

Recommended Posts

Hi Guys,

 

I aint too hot on php (more's the pity :( ), so if one of you clever guys could help me out with this I'd be very grateful.

 

Ok the script I am working with has the variables $listprice (which is the original price), $price (which is the latest price) & what I want to try to do is perform an equation using these variables, in order to produce a value that would then be assigned to $discount and displayed as a percentage.

 

Example:

 

$discount = ((($listprice - $price) / $listprice) * 100);
$content = str_replace("{discount}", $discount, $content);

 

Now whilst this will work perfectly if done manually using a calculator, it does not work in php ! it simply keeps returning a "0" irrespective of what the other values are.

 

Any ideas on this would be a great help & much appreciated  :confused:

Link to comment
Share on other sites

Hi requinix,

 

the values of $listprice & $price change with each article/product & ultimately so should the $discount variable that I'm trying to create. I've been trying a few things myself since posting on here & have succeeded in getting a test.php file to produce the correct figure when opened in my browser;

 

<?php
$listprice = 495;
$saving = 175;
// above values are dynamically assigned by the script as each new product article is created.
$discount = round (($saving / $listprice) * 100);
$content = str_replace("{discount}", $discount, $content);
echo $discount; ?>

 

The above code produces the figure 35 which is correct, however as soon as I try to add the following lines of code to the script it constantly returns a zero as the value !

 

$discount = round (($saving / $listprice) * 100);
$content = str_replace("{discount}", $discount, $content);

 

I know I'm almost there, just can't seem to solve this last problem  :shrug:

Link to comment
Share on other sites

Your code, copied and pasted.

 

<?php

$content = 'Today you have saved {discount}%!';

$listprice = 495;
$saving = 175;
// above values are dynamically assigned by the script as each new product article is created.
$discount = round (($saving / $listprice) * 100);
$content = str_replace("{discount}", $discount, $content);

echo $content;

?>

 

Returns

 

Today you have saved 35%!

 

So the issue has to be the values that aren't included in the area of code you're looking at. Bad input will give you bad output.

Link to comment
Share on other sites

@ requinix

 

the values of $listprice & $price change with each article/product & ultimately so should the $discount variable that I'm trying to create.

 

Doesn't that clearly state that the values are dynamic & continually changing..? So how can I give you any value for these variables...??? :confused:

 

Oh and yes when the article / post is finished then all values of prices are displayed in the following manner $??.?? Obviously the ? being replaced by the relevant figure!

Link to comment
Share on other sites

He means exactly what that variable contains WHEN you get that error.

 

We realize it's dynamic.

 

Did you simply ignore my solution?

 

No I most certainly did not ignore any offered solution or suggested code, if I don't respond immediately it means I am either busy or trying to impliment the code! Sorry but it takes me time as I don't know php like you guys do  :( and at 55 years old my brain is not as active or quick as it once was.

 

Hope that clarifies things..?

 

I'm assuming the variable your talking about is $discount & the error is that it always returns a zero "0" even though the other variables of $price & $saving or $listprice, would dictate that it should be a much higher figure than just zero!

Link to comment
Share on other sites

It's not so much about quickness, it's about taking the time to read and understand.

 

You said somewhere that you created place-holders for variables otherwise defined by the database. You need to verify that these values contain what you expect. To paraphrase; garbage in, garbage out.

 

The first thing you need to learn after basic syntax is how to debug. The first step is to make sure the data you're plugging into your code is what you expect. Add temporary echo's to see where it's messing up. Also, make sure error reporting is displayed (see signature).

 

<?php

$content = 'Today you have saved {discount}%!';

$listprice = 495;
$saving = 175;
// above values are dynamically assigned by the script as each new product article is created.
echo "About to perform round($saving / $listprice)<br>";
$discount = round (($saving / $listprice) * 100);
echo "Rounded, it's: $discount<br>";
echo "About to insert into '$content'<br>";
$content = str_replace("{discount}", $discount, $content);

echo "Final<br>$content";

?>

Link to comment
Share on other sites

It's not so much about quickness, it's about taking the time to read and understand.

 

@ xyph,

Yes understood, but this is exactly where I am having a problem, I don't yet know enough to understand & impliment the code you are offering as it is completely different to what is in the script I am using!

 

This is the extract from the script that defines the variables being used;

$content = str_replace("{price}", $price, $content);
$content = str_replace("{listprice}", $listprice, $content);
$savings = str_replace("$ ", "", $listprice) - str_replace("$ ", "", $price);
$content = str_replace("{savings}", $savings, $content);
    $discount = str_replace(($savings / $listprice) * 100);
    $content = str_replace("{discount}", round ($discount), $content);
$content = str_replace("{url}", $item->DetailPageURL, $content);	
$content = str_replace("{avgrating}", $item->CustomerReviews->AverageRating, $content);	
$content = str_replace("{reviewsnum}", $item->CustomerReviews->TotalReviews, $content);

 

In the template I am using if I place listprice, price or savings within curly brackets, it will return the correct value for each, relevant to that particular post/article. But if I try to do the same with discount it simply returns a zero "0". Yet if I take the two indented lines of code & add to a test.php with manually inserted values for $savings & $listprice, it works perfectly when opened in my browser and returns the correct discount value.

 

Hope that has made it clearer..?

Link to comment
Share on other sites

Either you've failed at copying and pasting your code, or you have not turned error reporting on, as I suggested.

That chunk of code will produce at the very least a WARNING error.

 

Also, your two indented lines are nearly identical to two of the lines in my code posted above. If you don't know where to put the debugging echo statements in, then I'm not sure I am capable of helping.

Link to comment
Share on other sites

@xyph,

Yes I do appologise, I must have copied the code from the wrong sheet, it should read;

 

$content = str_replace("{price}", $price, $content);
$content = str_replace("{listprice}", $listprice, $content);
$savings = str_replace("$ ", "", $listprice) - str_replace("$ ", "", $price);
$content = str_replace("{savings}", $savings, $content);
$discount = round (($saving / $listprice) * 100);
$content = str_replace("{discount}", $discount, $content);

 

Now when I originally started this thread, I politely asked if anyone could offer some assistance as php is not one of my strong points & as I have already stated my age, I thought that any sensible person would be able to grasp just how difficult it is for me to learn such a language at this age! I don't know how old you are, but I doubt you were born with this inbuilt knowledge & therefore just step back for a moment and remember just how difficult it was for you when you first started..? Or perhaps a better test would be to empty an entire Landrover engine or gearbox onto a table and see how you fair at rebuilding it (something I can do blindfolded).

 

Now nobody is forcing you to help anyone & if your own lack of understanding prevents you from doing so then so be it and I will bid you farwell & thankyou for the time you have spent on this, sorry you see it as a wasted effort!

 

But before I go I will say that you should understand that for many people that don't know this coding language, sites like this are an absolute treasure. But it can be difficult to come on here cap in hand asking for help, when very often a person may not even know what they are talking about or may not explain themselves using correct terminology & I do understand that this can make it difficult to offer an answer to a query. Nevertheless resorting to a bad attitude, sarcasm & rudeness is not the way to teach those that have come to you for help!  :(

Link to comment
Share on other sites

Steve,

 

The question being asked was do your variables ($price and $listprice) contain a numeric value such as 25.20 or do they contain your formatted value such as '$25.20'.  PHP cannot do math on string values, it has to convert them to a number first.  If your value contains non-numeric characters such as '$' or ',' then this conversion will fail and PHP will use 0, causing your math to come out incorrect.

 

When we ask you to verify or show us what your variables contain as a value, what we want you to do is echo them out just prior to your usage of them so that you can see what value they have at that particular point in time.  One of the better methods to use for this is the var_dump function.  In your case, you'd modify your code to look like this:

var_dump($listprice);
var_dump($price);
$discount = ((($listprice - $price) / $listprice) * 100);
var_dump($discount);
$content = str_replace("{discount}", $discount, $content);

 

then load your page.  You'd notice some extra output which would show you the exact values of those variables at that moment.

 

Link to comment
Share on other sites

Hi kicken,

Thankyou for such a clear & concise explantation, it does make a hell of a difference!

Ok I ammended the code to this, as you suggested;

$content = str_replace("{price}", $price, $content);
var_dump($price);	
$content = str_replace("{listprice}", $listprice, $content);
var_dump($listprice);
$savings = str_replace("$ ", "", $listprice) - str_replace("$ ", "", $price);
$content = str_replace("{savings}", $savings, $content);
var_dump($savings);
$discount = round (($savings / $listprice) * 100);
$content = str_replace("{discount}", $discount, $content);

 

And attempted to create a fresh post, but I got the following flashed up on the screen before even looking at the post;

string(0) "" string(0) "" int(0)

When I checked the post no values were displayed at all & no zero "0" either, just a blank space where the value used to be.

 

So if I understand this correctly, these values are being created as strings rather than numeric data & this is what is causing the problem..? Also explains why when I added values to these strings manually, (I only used numbers with no $ sign), it performed the calculation without any trouble at all!  Is that correct..??

 

Assuming this is the problem, how involved would it be to change the script to use numeric data instead of strings..? I have a feeling we are talking a lot of re-written script here..??

 

Thanks for your help Kicken at least now I have some clue as to what is going on  :D

Link to comment
Share on other sites

string(0) "" string(0) "" int(0)

 

string(0) "" indicates that your variable has no value.  It is an empty string, which when converted to a number is zero.  Your variables appear to not be getting the values you think they should.  Somewhere in your code prior to this you are not assigning them correctly, or not passing them to the page correctly.  You will need to start looking back through the code to find out where the error is.  Move the var_dump statements around your code at different places and use them to "trace" the code by seeing what the values of certain variables are at different points in the script.

 

Assuming this is the problem, how involved would it be to change the script to use numeric data instead of strings..?

 

PHP does not care too much about the actual type of the variables.  Having them be strings is ok, PHP will convert them to numbers when it needs to in order to do the math.  You just have to ensure that the value consists of only digits and a decimal point.  Any non-numeric characters such as a $ prefix or comma separator will cause PHP to fail to convert the value.

 

Link to comment
Share on other sites

You have the solution in your last code block. Whoever wrote that code strips out '$ ' before attempting to use the values arithmetically.

 

You're asking, cap in hand, for us to add functionality to code you haven't written, and then explain how we did it in hope that you might learn something.

 

Age has nothing to do with your inability to figure this stuff out... it's all in your approach to learning. Learn to walk before you crawl, or you'll forever be frustrated with solutions to your problems that you don't understand.

Link to comment
Share on other sites

You have the solution in your last code block. Whoever wrote that code strips out '$ ' before attempting to use the values arithmetically.

 

You're asking, cap in hand, for us to add functionality to code you haven't written, and then explain how we did it in hope that you might learn something.

 

Age has nothing to do with your inability to figure this stuff out... it's all in your approach to learning. Learn to walk before you crawl, or you'll forever be frustrated with solutions to your problems that you don't understand.

 

@ xyph

 

1. Ok YOU may see the solution in my last block of code, but unfortunately I do not! If I did then do you really think I would come on here asking for some assistance..?

 

2. At no point did I imply it was my code! And being unable to write or read and fully understand this code does not prevent me from having ideas that I think may improve the functionality of the script, or shall we all assume that once a script is written then that is as good as it will ever get..?

And yes why shouldn't I try to learn or has it suddenly been made a criminal act on this forum..?

Oh & thanks to Kicken I have now learnt about the use of var_dump().

 

3. You know nothing of my ability/inability to learn, but as you brought this up let me just inform you that if you take the time to check, there are several different styles & methods of learning "FACT" & unfortunately I have great difficulty in learning from books, because I am unable to relate to what they are talking about!

 

I am the type of person that learns best by hands on experience (practical as opposed to theory), so does my different method of learning make me any less of a person..? No! it simply means that throughout my entire life I have had to put up with very arrogant, self opinionated, self righteous people that could not teach if their life depended on it!

 

Perhaps when you have a moment free you may care to read what is said here: - http://people.usd.edu/~bwjames/tut/learning-style/styleres.html about Kinesthetic Learners.

 

Then perhaps you may have a better understanding of why I appear to try to run before I can walk!

Link to comment
Share on other sites

Regardless of the 'way' you learn, you need to learn the basics first.

 

You're jumping in attempting to swap place-holders and isolate specific values from a string. I don't see how you could properly understand a solution to that problem when you don't know how to verify what values these strings contain. Even more important, it doesn't seem you know where these variables are being populated.

 

Why are you taking my advice as an attack? You're jumping on the defensive when I'm really trying to help you. The forum you've posted in is for people to get help with their own code. There's a 3rd Party PHP Scripts forum, where you can ask people to help you modify something beyond your current ability.

 

I'm not calling you stupid, I'm saying you won't learn anything - especially being harder for you to learn in the first place, as a hands-on learner - if you dive in head first. There's variables, there's conditionals and loops, operators and functions as well as terminology you need to learn before trying to modify that script - even with our guiding advice.

 

In response,

 

1. I expect you to understand what each line is meant to do. If not, I expect you to ask about a specific function call or line you don't understand.

2. It's neat that you're coming up with functionality you'd like to see in someone else's program. You shouldn't expect us to implement that, or hold your hand through every step. Again, the solution to your problem has been posted many, many times. We don't get paid, so you shouldn't expect much more than a helpful nudge in the right direction.

3. I brought it up? It was your initial excuse.

Sorry but it takes me time as I don't know php like you guys do  and at 55 years old my brain is not as active or quick as it once was.

 

The link you posted has nothing about trying to run before you walk.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.