osanger
osanger

Reputation: 2352

Floatvalue is always float(0)

i want to calculate a shipping-price.

My Code:

    $item_count = self::getItemCount();
    if($item_count == 1){
        $vsk = 2.5;
    }
    else if($item_count > 1 && $item_count <= 10){
        $vsk = 4.5;
    }
    else{
        $vsk = ceil($item_count/10) * 4.5;
    }
    var_dump($item_count);
    var_dump($vsk);

$item_count contains the number of items in the cart and gets me the right value. But a vardump of $vsk is always float(0);

Some examples:

string(3) "(1)" float(0)
string(3) "(4)" float(0)

Do you see my mistake(s) ?

EDIT:

arkascha noticed that getItemCOunt returns a string. I cahnge the code to:

$item_count = intval(self::getItemCount());

now i receive:

int(0) float(0)

So my Item-Count-method seems to be wrong.

public static function getItemCount()
{
    self::$items = session::getArray('cart');
    $amount = 0;
    foreach (self::$items as $i) {
        $amount += $i;
    }
    return ($amount > 0) ? '(' . $amount . ')' : '';
}

Upvotes: 0

Views: 50

Answers (1)

Damien Pirsy
Damien Pirsy

Reputation: 25435

I see too many parenthesis there:

string(3) "(1)"

If you cast that to int, it becomes 0 (it's the string (1), not 1 !), and that fawls all your subsequent calculations.

You need to return just "1", either a string or an int (php is loosely typed, remember), and if you want to be more sure cast that to int().

Eliminate those parenthesis in your $item_count, i.e. make self::getItemCount() return only the number. If you can't for any reason, just remove it afterwards, something like $item_count = str_replace(['(',')'], '', self::getItemCount()), bu the best course of action would be to just return a number

Upvotes: 2

Related Questions