-3

I am trying to create a simple script to add to my html website.

I need it to calculate the price based on the quantity the user inputs.

For example, a value of 1-1000 will be multiplied by 1.50 and displayed, 1001-5000 multiplied by 1.20 and displayed, 5001-10000 multiplied by 1 and displayed and any number above that would display an error message like "Must be below 10000".

I've been trying to do this in php with no success.

4 Answers4

1

You can use if to to check the vault and diplay the calculated value:

if($input <= 1000)
{
  echo $input * 1.5;
}
elseif($input <= 5000)
{
  echo $input * 1.2;
}
elseif($input <= 10000)
{
  echo $input;
}
else
{
  echo "Must be below 10000";
}
moonlight
  • 359
  • 6
  • 17
1

You may find operator switch very useful (Switch in PHP). Something like this:

...
switch ($quantity) {
    case (($quantity >= 1) && ($quantity <= 1000)):
        $multiplicator = 1.5;
        echo $quantity * $multiplicator;
        break;
    case (($quantity >= 1001) && ($quantity <= 5000)):
        $multiplicator = 1.2;
        echo $quantity * $multiplicator;
        break;
    case (($quantity >= 5001) && ($quantity <= 10000)):
        $multiplicator = 1.2;
        echo $quantity * $multiplicator;
        break;
    case ($quantity > 10000):
        echo 'Quantity must be less then 10000!';
        break;
}
....

Edited: another option using loop:

...
$limits_array = array(
    0 => array(
        'min' => 1,
        'max' => 1000,
        'mul' => 1.5,
    ),
    1 => array(
        'min' => 1001,
        'max' => 5000,
        'mul' => 1.2,
    ),
    2 => array(
        'min' => 5001,
        'max' => 10000,
        'mul' => 1,
    ),
);
foreach ($limits_array as $limits)
    if (($quantity >= $limits['min']) && ($quantity <= $limits['max']) {
        echo $quantity * $limits['mul'];
        break;
    }
if ($quantity > $limits['max'])
    echo 'Quantity must be less then 10000!';
...

Please notice, that after foreach last value element ($value is a common name for it, there it is $limits) still stores the last item from array. Take a look at brackets.

Bandydan
  • 623
  • 1
  • 8
  • 24
  • Why? What if the conditions became 100? 100 cases? Shouldn't the common functionality (IF and MULTIPLY) be NOT replicated? – Royal Bg Nov 03 '13 at 11:12
  • Well, because it is simpler to explain, if you are new to php. I think that this task is kind of a test in university for knowing or not knowing conditional operators, but not of writing ideal code :) BTW, I think that would be faster then defining a lot of constants and looping through, especially if you do some string operations. – Bandydan Nov 03 '13 at 11:15
  • You could never be sure :) He never told even that PHP is the final variant he wants, just that he tried with PHP :)) btw. I saw your edit with array, which @YuraSokolov suggested to me. I'm interested why do you think most of these values like max and min (and the multiplier, but it may vary I guess in further logic expansion) are not constants :) I mean, you will never change something over $limits['min'] or $limits['max'], why it should be a variable – Royal Bg Nov 03 '13 at 11:37
  • That's true, it was only my guess. Just... it is a student question and quite common university task ;) I started adding array after your comment, not Yuriy. As for constants... I believe they are very useful to store something really meaning, and to store that in a project, not a single file and not in a simple task. I like to store there md5 and sha1 keys for api-s, some language constants etc.. In this particular keys all digits seems to me not a constant, but only a value to compare with. Once. So - it is array as the most. – Bandydan Nov 03 '13 at 11:42
  • I was always used to use defining arrays with not so static values. I mean you have in your code defined array, with each key, each subkey and each value constant(static) added. I would use an array if there's something dynamic, the keys or the values are comming from early defined variable or constant, or to push dynamic data into array, which lately can be used. The same logic of meaningful as you stated:) But when I think twice, there's no other why in PHP, is it? I mean in other languages there are maps, here not? :) – Royal Bg Nov 03 '13 at 11:57
  • true) Anyway, in such a project it does not matter. I think we gave @Emmanuel enough options) – Bandydan Nov 03 '13 at 11:59
0

Instead of defining every condition in an IF statement, I would suggest defining constants for every stage:

<form action="" method="post">
    <input type="text" name="qnt" />
    <input type="submit" />
</form>

<?php

define('MIN_STAGE', 1);
define('MAX_STAGE', 3);
define('STAGE_1_MIN', 0);
define('STAGE_1_MAX', 1000);
define('STAGE_1_MULTIPLIER', 1.50);
define('STAGE_2_MIN', STAGE_1_MAX);
define('STAGE_2_MAX', 5000);
define('STAGE_2_MULTIPLIER', 1.20);
define('STAGE_3_MIN', STAGE_2_MAX);
define('STAGE_3_MAX', 10000);
define('STAGE_3_MULTIPLIER', 1);

for($i = MIN_STAGE; $i <= MAX_STAGE; $i++) {
    if ($_POST['qnt'] > constant("STAGE_".$i."_MIN") && $_POST['qnt'] <= constant("STAGE_".$i."_MAX")) {
        echo $_POST['qnt'] * constant("STAGE_".$i."_MULTIPLIER");
    }
    elseif ($_POST['qnt'] < constant("STAGE_".MIN_STAGE."_MIN") || $_POST['qnt'] > constant("STAGE_".MAX_STAGE."_MAX")) {
        die ('Must be between ' . constant("STAGE_".MIN_STAGE."_MIN") . ' AND ' . constant("STAGE_".MAX_STAGE."_MAX"));
    }
}
Royal Bg
  • 6,988
  • 1
  • 18
  • 24
  • Interesting use of constants there! I think I might have selected an array for this task - accessing entries is a bit easier. – halfer Nov 03 '13 at 11:18
  • 1
    To many constants is not so good. This solution can be better is instead of constans you would use array. Like so: array('stage1'=>array('min'=>1,'max'=>1000,'multiplier'=>1.5)); And the just a foreach loop on this array. – Yura Sokolov Nov 03 '13 at 11:20
  • I was between an array to map the stage properties, and constants, even though building a constant like `constant('something'.$var)` is not my favourite choice, I thought every of these entries is actually a constant – Royal Bg Nov 03 '13 at 11:21
  • @YuraSokolov I am not telling this is the best solution, but I saw "Too many constants is not so good", so can you clarify why? I was interested in that and make a simple google search, led me to: http://stackoverflow.com/questions/1249303/too-many-constants ... from the answers I see there's no rule for too many constants, if they encapsulate something to build logic on it. Maybe in the case here we can get rid of the _MIN constants and make logic over it, but still it seems for me that these values are constants itself. – Royal Bg Nov 03 '13 at 11:31
  • @RoyalBg, first of all this: http://stackoverflow.com/a/7766545/2651326 and the code with many "define"s is ugly. I prefer to insert the constants in static class and to define them in classic OOP style. – Yura Sokolov Nov 03 '13 at 11:37
  • @YuraSokolov this is more as an inproper why of defining constants, however inside a class you are obligated to use `const` so it doesn't really bother the things. If `const` is faster, I can edit my code with changing define() to const, but still we will have "Too many constants", it doesn't seem like it's a bad design using many constants – Royal Bg Nov 03 '13 at 11:40
  • @RoyalBg, you are forgetting, that a lot easier to loop through an array, then through constants. Instead of foreach loop, you are adding two more constants and a variable. For sure this is not the thing that will slow down current code, but in big project it can turn out, that you have hundreds of variables and/or constants that you was able to prevent. – Yura Sokolov Nov 03 '13 at 11:47
0

If you want it in pure php - that is not so good. To many reloads, but here how it works(it's a bad code, for bad idea):

<?php
$price = 10;
if(isset($_REQUEST['count']){
    $count = (int)$count;
    if($count > 10000){
        echo 'Must be below 10000';
    }
    elseif($count >= 1 && $count <= 1000){
        $price *= 1.2;
    }
    //Etc...
    $total = $price * $count;
}

In my opinion, you should try achieve it with JS(or easier - with jQuery). First of all, create a form:

<input type="text" id="count" />
<input type="button" id="calculate" value="Calculate" />

Then do something like this:

$(function(){
    var price = 10;
    var multiplier = 1;
    $('#calculate').click(function(){
        var count = parseInt($('#count').val());
        if(count > 10000){
            alert('Must be below 10000');
            return;
        }
        else if(count >= 1 && count <= 1000){
            multiplier = 1.2;
        }
        alert('Current price is ' + price + ' * ' + multiplier + ' = ' + getActualPrice());
    });

    function getActualPrice(){
        return price * multiplier;
    }
});

Fiddle

Yura Sokolov
  • 207
  • 4
  • 13