jeudi 23 avril 2015

Change global 2d array from a function PHP?

$q = $_POST['q'];

$inCart = isset($_COOKIE['cart']) ? unserialize($_COOKIE['cart']) : array();

function alreadyInCart() {

    global $inCart, $good, $q;

    foreach ($inCart as $inCart1) {

        if ($inCart1[0] == $good->id) { // if this good already in cart

            $inCart1[1] = $inCart1[1] + $q; // write sum of q's to existing array

            return true; // and return true

        }

    }

    return false; // return false if not

}


if (alreadyInCart() == false) { // if good added to cart for the first time

    $inCart[] = array($good->id, $q); // add array at the end of array

}

Hello. So my problem is that I'm running a function to find out if $good->id is already inside of 2d $inCart array.

$inCart looks something like this:

Array
(
    [0] => Array
        (
            [0] => 6
            [1] => 1
        )

    [1] => Array
        (
            [0] => 5
            [1] => 1
        )

)

Where [0] is a good ID and [1] is an amount of this good in a cart.

So I tracked that function actually does what I want and returns true/false as expected, but looks like it only does it inside of itself. Cause if I put print_r($inCart1[1]) inside of a function it does add up and outputs the sum, as expected. But when I output the array at the end of the code (outside the function) the amount doesn't add up, just stays how it was before the function run.

Any ideas why that happens?

Aucun commentaire:

Enregistrer un commentaire