Updating a specific key within a multidimensional array (PHP)












0















I'm having some difficulty updating a quantity value in a multi-dimensional array I've created and really hoping you can help me correct where I've gone wrong;



.



The background



I've got two "items" which both have a simple form tag followed by a hidden input field with a unique value (1 for the first item, 2 for the second).
The button will just point back to this same page using the POST method.



The div on the right of the page will then load a "basket" which will use these post values and add them to an array.



When the "add" button is used again the value should update to +1 rather than create another sub_array.



.



What is currently happening



Currently when I click "add" the first time it adds the array as expected;



Result 1



However when clicking "add" for the second time it adds a second array rather than +1'in the quantity.



Result 2



On the third time clicking "add" it does actually now find the original value and update it as I expected, if I click again and again it will continue to update the quantity



Result 3



It just seems to be that second time I click "add".



.



The Script



<?php session_start();

function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}

return false;
}

if (ISSET($_POST["prod"]))
{
if(in_array($_POST["prod"],$_SESSION["cart"])==TRUE)
{
$_SESSION["cart"][0] =
array($_POST["prod"],$_POST["name"],$_SESSION["cart"][0][2]+1);
}
else{
echo 'running else';
$_SESSION["cart"]=array($_POST["prod"],$_POST["name"],1);}}

if ($_POST['e']=='1')
{
$_SESSION['cart'] = '';
}
echo '<br /><br />';
print_r($_SESSION["cart"]);
}


Sample form



<form action="test.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
<input type="hidden" value="1" name="prod" />
<input type="hidden" value="MAST-O-MIR" name="name" />
<button class="plus-btn" type="Submit">Add</button>
</form>


Also, what you might well notice from my script is that when you "add" the second item it will actually overwrite the first one by creating the array from scratch so if you can help me with either or both of these I really would appreciate the expertise!



Many thanks to all in advance!










share|improve this question

























  • This is difficult to understand without a sample form.

    – Progrock
    Nov 28 '18 at 13:15
















0















I'm having some difficulty updating a quantity value in a multi-dimensional array I've created and really hoping you can help me correct where I've gone wrong;



.



The background



I've got two "items" which both have a simple form tag followed by a hidden input field with a unique value (1 for the first item, 2 for the second).
The button will just point back to this same page using the POST method.



The div on the right of the page will then load a "basket" which will use these post values and add them to an array.



When the "add" button is used again the value should update to +1 rather than create another sub_array.



.



What is currently happening



Currently when I click "add" the first time it adds the array as expected;



Result 1



However when clicking "add" for the second time it adds a second array rather than +1'in the quantity.



Result 2



On the third time clicking "add" it does actually now find the original value and update it as I expected, if I click again and again it will continue to update the quantity



Result 3



It just seems to be that second time I click "add".



.



The Script



<?php session_start();

function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}

return false;
}

if (ISSET($_POST["prod"]))
{
if(in_array($_POST["prod"],$_SESSION["cart"])==TRUE)
{
$_SESSION["cart"][0] =
array($_POST["prod"],$_POST["name"],$_SESSION["cart"][0][2]+1);
}
else{
echo 'running else';
$_SESSION["cart"]=array($_POST["prod"],$_POST["name"],1);}}

if ($_POST['e']=='1')
{
$_SESSION['cart'] = '';
}
echo '<br /><br />';
print_r($_SESSION["cart"]);
}


Sample form



<form action="test.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
<input type="hidden" value="1" name="prod" />
<input type="hidden" value="MAST-O-MIR" name="name" />
<button class="plus-btn" type="Submit">Add</button>
</form>


Also, what you might well notice from my script is that when you "add" the second item it will actually overwrite the first one by creating the array from scratch so if you can help me with either or both of these I really would appreciate the expertise!



Many thanks to all in advance!










share|improve this question

























  • This is difficult to understand without a sample form.

    – Progrock
    Nov 28 '18 at 13:15














0












0








0








I'm having some difficulty updating a quantity value in a multi-dimensional array I've created and really hoping you can help me correct where I've gone wrong;



.



The background



I've got two "items" which both have a simple form tag followed by a hidden input field with a unique value (1 for the first item, 2 for the second).
The button will just point back to this same page using the POST method.



The div on the right of the page will then load a "basket" which will use these post values and add them to an array.



When the "add" button is used again the value should update to +1 rather than create another sub_array.



.



What is currently happening



Currently when I click "add" the first time it adds the array as expected;



Result 1



However when clicking "add" for the second time it adds a second array rather than +1'in the quantity.



Result 2



On the third time clicking "add" it does actually now find the original value and update it as I expected, if I click again and again it will continue to update the quantity



Result 3



It just seems to be that second time I click "add".



.



The Script



<?php session_start();

function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}

return false;
}

if (ISSET($_POST["prod"]))
{
if(in_array($_POST["prod"],$_SESSION["cart"])==TRUE)
{
$_SESSION["cart"][0] =
array($_POST["prod"],$_POST["name"],$_SESSION["cart"][0][2]+1);
}
else{
echo 'running else';
$_SESSION["cart"]=array($_POST["prod"],$_POST["name"],1);}}

if ($_POST['e']=='1')
{
$_SESSION['cart'] = '';
}
echo '<br /><br />';
print_r($_SESSION["cart"]);
}


Sample form



<form action="test.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
<input type="hidden" value="1" name="prod" />
<input type="hidden" value="MAST-O-MIR" name="name" />
<button class="plus-btn" type="Submit">Add</button>
</form>


Also, what you might well notice from my script is that when you "add" the second item it will actually overwrite the first one by creating the array from scratch so if you can help me with either or both of these I really would appreciate the expertise!



Many thanks to all in advance!










share|improve this question
















I'm having some difficulty updating a quantity value in a multi-dimensional array I've created and really hoping you can help me correct where I've gone wrong;



.



The background



I've got two "items" which both have a simple form tag followed by a hidden input field with a unique value (1 for the first item, 2 for the second).
The button will just point back to this same page using the POST method.



The div on the right of the page will then load a "basket" which will use these post values and add them to an array.



When the "add" button is used again the value should update to +1 rather than create another sub_array.



.



What is currently happening



Currently when I click "add" the first time it adds the array as expected;



Result 1



However when clicking "add" for the second time it adds a second array rather than +1'in the quantity.



Result 2



On the third time clicking "add" it does actually now find the original value and update it as I expected, if I click again and again it will continue to update the quantity



Result 3



It just seems to be that second time I click "add".



.



The Script



<?php session_start();

function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}

return false;
}

if (ISSET($_POST["prod"]))
{
if(in_array($_POST["prod"],$_SESSION["cart"])==TRUE)
{
$_SESSION["cart"][0] =
array($_POST["prod"],$_POST["name"],$_SESSION["cart"][0][2]+1);
}
else{
echo 'running else';
$_SESSION["cart"]=array($_POST["prod"],$_POST["name"],1);}}

if ($_POST['e']=='1')
{
$_SESSION['cart'] = '';
}
echo '<br /><br />';
print_r($_SESSION["cart"]);
}


Sample form



<form action="test.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
<input type="hidden" value="1" name="prod" />
<input type="hidden" value="MAST-O-MIR" name="name" />
<button class="plus-btn" type="Submit">Add</button>
</form>


Also, what you might well notice from my script is that when you "add" the second item it will actually overwrite the first one by creating the array from scratch so if you can help me with either or both of these I really would appreciate the expertise!



Many thanks to all in advance!







php algorithm multidimensional-array logic






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 28 '18 at 14:08







Simon

















asked Nov 28 '18 at 13:01









SimonSimon

489




489













  • This is difficult to understand without a sample form.

    – Progrock
    Nov 28 '18 at 13:15



















  • This is difficult to understand without a sample form.

    – Progrock
    Nov 28 '18 at 13:15

















This is difficult to understand without a sample form.

– Progrock
Nov 28 '18 at 13:15





This is difficult to understand without a sample form.

– Progrock
Nov 28 '18 at 13:15












2 Answers
2






active

oldest

votes


















1














I tried to debug your code and a possible solution could be the following:



<?php

session_start();

if(!isset($_SESSION["cart"]))
{
$_SESSION["cart"]=;
}

if (isset($_POST["prod"]))
{
$prod_id=$_POST["prod"];
//let suppose $_POST['prod'] is your item id
$found=false;
for($i=0;$i<count($_SESSION['cart']);$i++)
{
if(isset($_SESSION['cart'][$prod_id]))
{
echo "found! so add +1";
$_SESSION['cart'][$prod_id][2]+=1;
$found=true;
break;
}
}
if($found==false)
{
echo 'not found! so create a new item';
$_SESSION["cart"][$prod_id]=array($_POST["prod"],$_POST["name"],1);
}
}

if (isset($_POST['e']) && $_POST['e']=='1')
{
$_SESSION['cart'] = '';
}

echo '<br /><br />';
print_r($_SESSION["cart"]);

?>
<form action="cart.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
<input type="hidden" value="1" name="prod" />
<input type="hidden" value="MAST-O-MIR" name="name" />
<button class="plus-btn" type="Submit">Add</button>
</form>
<form action="cart.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
<input type="hidden" value="2" name="prod" />
<input type="hidden" value="MAST-O-MIR" name="name" />
<button class="plus-btn" type="Submit">Add</button>
</form>


Another way to do it is using associative arrays.
The following code creates a cart array in $_SESSION using the item name as key(so you don't need to loop over the cart array to find the item) and
an array with properties as name=>value for each item.



session_start();

if(!isset($_SESSION["cart"]))
{
$_SESSION["cart"]=;
}
//let's suppose you have unique names for items
if (isset($_POST["prod"]))
{
$name=$_POST["name"];
if(isset($_SESSION['cart'][$name]))
{
echo "found! so add +1";
$_SESSION['cart'][$name]['quantity']+=1;
}
else
{
echo 'not found! so create a new item';
$_SESSION["cart"][$name]=array("id"=>$_POST["prod"],"name"=>$_POST["name"],"quantity"=>1);
}
}

if (isset($_POST['e']) && $_POST['e']=='1')
{
$_SESSION['cart'] =;
}

echo '<br /><br />';
print_r($_SESSION["cart"]);

?>
<form action="cart2.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
<input type="hidden" value="1" name="prod" />
<input type="hidden" value="MAST-O-MIR" name="name" />
<button class="plus-btn" type="Submit">Add</button>
</form>
<form action="cart2.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
<input type="hidden" value="2" name="prod" />
<input type="hidden" value="MAST-OMIR" name="name" />
<button class="plus-btn" type="Submit">Add</button>
</form>





share|improve this answer































    0














    It's hard to test your code without a sample form but I guess both of your problems may be solved by replacing:



    $_SESSION["cart"][0] = array($_POST["prod"], $_POST["name"], $_SESSION["cart"][0][2]+1);


    For:



    $_SESSION["cart"][0][2]+= 1;


    By the way, try to properly indent your code when you are going to post it. It is hard to read.






    share|improve this answer
























    • Thanks Cool Guy, I've added the sample form as you suggested and in the meantime I'll give this a go

      – Simon
      Nov 28 '18 at 14:43











    • This doesn't work, after adding the first items and then clicking "add" for the second it just stops processing and then I can't see any of my basket or items on the screen until I reset the array

      – Simon
      Nov 28 '18 at 16:25











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53520086%2fupdating-a-specific-key-within-a-multidimensional-array-php%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    I tried to debug your code and a possible solution could be the following:



    <?php

    session_start();

    if(!isset($_SESSION["cart"]))
    {
    $_SESSION["cart"]=;
    }

    if (isset($_POST["prod"]))
    {
    $prod_id=$_POST["prod"];
    //let suppose $_POST['prod'] is your item id
    $found=false;
    for($i=0;$i<count($_SESSION['cart']);$i++)
    {
    if(isset($_SESSION['cart'][$prod_id]))
    {
    echo "found! so add +1";
    $_SESSION['cart'][$prod_id][2]+=1;
    $found=true;
    break;
    }
    }
    if($found==false)
    {
    echo 'not found! so create a new item';
    $_SESSION["cart"][$prod_id]=array($_POST["prod"],$_POST["name"],1);
    }
    }

    if (isset($_POST['e']) && $_POST['e']=='1')
    {
    $_SESSION['cart'] = '';
    }

    echo '<br /><br />';
    print_r($_SESSION["cart"]);

    ?>
    <form action="cart.php" method="post" enctype="application/x-www-form-urlencoded">
    MAST-O-MIR<br/>
    img<br/>
    £2.00<br/>
    <input type="hidden" value="1" name="prod" />
    <input type="hidden" value="MAST-O-MIR" name="name" />
    <button class="plus-btn" type="Submit">Add</button>
    </form>
    <form action="cart.php" method="post" enctype="application/x-www-form-urlencoded">
    MAST-O-MIR<br/>
    img<br/>
    £2.00<br/>
    <input type="hidden" value="2" name="prod" />
    <input type="hidden" value="MAST-O-MIR" name="name" />
    <button class="plus-btn" type="Submit">Add</button>
    </form>


    Another way to do it is using associative arrays.
    The following code creates a cart array in $_SESSION using the item name as key(so you don't need to loop over the cart array to find the item) and
    an array with properties as name=>value for each item.



    session_start();

    if(!isset($_SESSION["cart"]))
    {
    $_SESSION["cart"]=;
    }
    //let's suppose you have unique names for items
    if (isset($_POST["prod"]))
    {
    $name=$_POST["name"];
    if(isset($_SESSION['cart'][$name]))
    {
    echo "found! so add +1";
    $_SESSION['cart'][$name]['quantity']+=1;
    }
    else
    {
    echo 'not found! so create a new item';
    $_SESSION["cart"][$name]=array("id"=>$_POST["prod"],"name"=>$_POST["name"],"quantity"=>1);
    }
    }

    if (isset($_POST['e']) && $_POST['e']=='1')
    {
    $_SESSION['cart'] =;
    }

    echo '<br /><br />';
    print_r($_SESSION["cart"]);

    ?>
    <form action="cart2.php" method="post" enctype="application/x-www-form-urlencoded">
    MAST-O-MIR<br/>
    img<br/>
    £2.00<br/>
    <input type="hidden" value="1" name="prod" />
    <input type="hidden" value="MAST-O-MIR" name="name" />
    <button class="plus-btn" type="Submit">Add</button>
    </form>
    <form action="cart2.php" method="post" enctype="application/x-www-form-urlencoded">
    MAST-O-MIR<br/>
    img<br/>
    £2.00<br/>
    <input type="hidden" value="2" name="prod" />
    <input type="hidden" value="MAST-OMIR" name="name" />
    <button class="plus-btn" type="Submit">Add</button>
    </form>





    share|improve this answer




























      1














      I tried to debug your code and a possible solution could be the following:



      <?php

      session_start();

      if(!isset($_SESSION["cart"]))
      {
      $_SESSION["cart"]=;
      }

      if (isset($_POST["prod"]))
      {
      $prod_id=$_POST["prod"];
      //let suppose $_POST['prod'] is your item id
      $found=false;
      for($i=0;$i<count($_SESSION['cart']);$i++)
      {
      if(isset($_SESSION['cart'][$prod_id]))
      {
      echo "found! so add +1";
      $_SESSION['cart'][$prod_id][2]+=1;
      $found=true;
      break;
      }
      }
      if($found==false)
      {
      echo 'not found! so create a new item';
      $_SESSION["cart"][$prod_id]=array($_POST["prod"],$_POST["name"],1);
      }
      }

      if (isset($_POST['e']) && $_POST['e']=='1')
      {
      $_SESSION['cart'] = '';
      }

      echo '<br /><br />';
      print_r($_SESSION["cart"]);

      ?>
      <form action="cart.php" method="post" enctype="application/x-www-form-urlencoded">
      MAST-O-MIR<br/>
      img<br/>
      £2.00<br/>
      <input type="hidden" value="1" name="prod" />
      <input type="hidden" value="MAST-O-MIR" name="name" />
      <button class="plus-btn" type="Submit">Add</button>
      </form>
      <form action="cart.php" method="post" enctype="application/x-www-form-urlencoded">
      MAST-O-MIR<br/>
      img<br/>
      £2.00<br/>
      <input type="hidden" value="2" name="prod" />
      <input type="hidden" value="MAST-O-MIR" name="name" />
      <button class="plus-btn" type="Submit">Add</button>
      </form>


      Another way to do it is using associative arrays.
      The following code creates a cart array in $_SESSION using the item name as key(so you don't need to loop over the cart array to find the item) and
      an array with properties as name=>value for each item.



      session_start();

      if(!isset($_SESSION["cart"]))
      {
      $_SESSION["cart"]=;
      }
      //let's suppose you have unique names for items
      if (isset($_POST["prod"]))
      {
      $name=$_POST["name"];
      if(isset($_SESSION['cart'][$name]))
      {
      echo "found! so add +1";
      $_SESSION['cart'][$name]['quantity']+=1;
      }
      else
      {
      echo 'not found! so create a new item';
      $_SESSION["cart"][$name]=array("id"=>$_POST["prod"],"name"=>$_POST["name"],"quantity"=>1);
      }
      }

      if (isset($_POST['e']) && $_POST['e']=='1')
      {
      $_SESSION['cart'] =;
      }

      echo '<br /><br />';
      print_r($_SESSION["cart"]);

      ?>
      <form action="cart2.php" method="post" enctype="application/x-www-form-urlencoded">
      MAST-O-MIR<br/>
      img<br/>
      £2.00<br/>
      <input type="hidden" value="1" name="prod" />
      <input type="hidden" value="MAST-O-MIR" name="name" />
      <button class="plus-btn" type="Submit">Add</button>
      </form>
      <form action="cart2.php" method="post" enctype="application/x-www-form-urlencoded">
      MAST-O-MIR<br/>
      img<br/>
      £2.00<br/>
      <input type="hidden" value="2" name="prod" />
      <input type="hidden" value="MAST-OMIR" name="name" />
      <button class="plus-btn" type="Submit">Add</button>
      </form>





      share|improve this answer


























        1












        1








        1







        I tried to debug your code and a possible solution could be the following:



        <?php

        session_start();

        if(!isset($_SESSION["cart"]))
        {
        $_SESSION["cart"]=;
        }

        if (isset($_POST["prod"]))
        {
        $prod_id=$_POST["prod"];
        //let suppose $_POST['prod'] is your item id
        $found=false;
        for($i=0;$i<count($_SESSION['cart']);$i++)
        {
        if(isset($_SESSION['cart'][$prod_id]))
        {
        echo "found! so add +1";
        $_SESSION['cart'][$prod_id][2]+=1;
        $found=true;
        break;
        }
        }
        if($found==false)
        {
        echo 'not found! so create a new item';
        $_SESSION["cart"][$prod_id]=array($_POST["prod"],$_POST["name"],1);
        }
        }

        if (isset($_POST['e']) && $_POST['e']=='1')
        {
        $_SESSION['cart'] = '';
        }

        echo '<br /><br />';
        print_r($_SESSION["cart"]);

        ?>
        <form action="cart.php" method="post" enctype="application/x-www-form-urlencoded">
        MAST-O-MIR<br/>
        img<br/>
        £2.00<br/>
        <input type="hidden" value="1" name="prod" />
        <input type="hidden" value="MAST-O-MIR" name="name" />
        <button class="plus-btn" type="Submit">Add</button>
        </form>
        <form action="cart.php" method="post" enctype="application/x-www-form-urlencoded">
        MAST-O-MIR<br/>
        img<br/>
        £2.00<br/>
        <input type="hidden" value="2" name="prod" />
        <input type="hidden" value="MAST-O-MIR" name="name" />
        <button class="plus-btn" type="Submit">Add</button>
        </form>


        Another way to do it is using associative arrays.
        The following code creates a cart array in $_SESSION using the item name as key(so you don't need to loop over the cart array to find the item) and
        an array with properties as name=>value for each item.



        session_start();

        if(!isset($_SESSION["cart"]))
        {
        $_SESSION["cart"]=;
        }
        //let's suppose you have unique names for items
        if (isset($_POST["prod"]))
        {
        $name=$_POST["name"];
        if(isset($_SESSION['cart'][$name]))
        {
        echo "found! so add +1";
        $_SESSION['cart'][$name]['quantity']+=1;
        }
        else
        {
        echo 'not found! so create a new item';
        $_SESSION["cart"][$name]=array("id"=>$_POST["prod"],"name"=>$_POST["name"],"quantity"=>1);
        }
        }

        if (isset($_POST['e']) && $_POST['e']=='1')
        {
        $_SESSION['cart'] =;
        }

        echo '<br /><br />';
        print_r($_SESSION["cart"]);

        ?>
        <form action="cart2.php" method="post" enctype="application/x-www-form-urlencoded">
        MAST-O-MIR<br/>
        img<br/>
        £2.00<br/>
        <input type="hidden" value="1" name="prod" />
        <input type="hidden" value="MAST-O-MIR" name="name" />
        <button class="plus-btn" type="Submit">Add</button>
        </form>
        <form action="cart2.php" method="post" enctype="application/x-www-form-urlencoded">
        MAST-O-MIR<br/>
        img<br/>
        £2.00<br/>
        <input type="hidden" value="2" name="prod" />
        <input type="hidden" value="MAST-OMIR" name="name" />
        <button class="plus-btn" type="Submit">Add</button>
        </form>





        share|improve this answer













        I tried to debug your code and a possible solution could be the following:



        <?php

        session_start();

        if(!isset($_SESSION["cart"]))
        {
        $_SESSION["cart"]=;
        }

        if (isset($_POST["prod"]))
        {
        $prod_id=$_POST["prod"];
        //let suppose $_POST['prod'] is your item id
        $found=false;
        for($i=0;$i<count($_SESSION['cart']);$i++)
        {
        if(isset($_SESSION['cart'][$prod_id]))
        {
        echo "found! so add +1";
        $_SESSION['cart'][$prod_id][2]+=1;
        $found=true;
        break;
        }
        }
        if($found==false)
        {
        echo 'not found! so create a new item';
        $_SESSION["cart"][$prod_id]=array($_POST["prod"],$_POST["name"],1);
        }
        }

        if (isset($_POST['e']) && $_POST['e']=='1')
        {
        $_SESSION['cart'] = '';
        }

        echo '<br /><br />';
        print_r($_SESSION["cart"]);

        ?>
        <form action="cart.php" method="post" enctype="application/x-www-form-urlencoded">
        MAST-O-MIR<br/>
        img<br/>
        £2.00<br/>
        <input type="hidden" value="1" name="prod" />
        <input type="hidden" value="MAST-O-MIR" name="name" />
        <button class="plus-btn" type="Submit">Add</button>
        </form>
        <form action="cart.php" method="post" enctype="application/x-www-form-urlencoded">
        MAST-O-MIR<br/>
        img<br/>
        £2.00<br/>
        <input type="hidden" value="2" name="prod" />
        <input type="hidden" value="MAST-O-MIR" name="name" />
        <button class="plus-btn" type="Submit">Add</button>
        </form>


        Another way to do it is using associative arrays.
        The following code creates a cart array in $_SESSION using the item name as key(so you don't need to loop over the cart array to find the item) and
        an array with properties as name=>value for each item.



        session_start();

        if(!isset($_SESSION["cart"]))
        {
        $_SESSION["cart"]=;
        }
        //let's suppose you have unique names for items
        if (isset($_POST["prod"]))
        {
        $name=$_POST["name"];
        if(isset($_SESSION['cart'][$name]))
        {
        echo "found! so add +1";
        $_SESSION['cart'][$name]['quantity']+=1;
        }
        else
        {
        echo 'not found! so create a new item';
        $_SESSION["cart"][$name]=array("id"=>$_POST["prod"],"name"=>$_POST["name"],"quantity"=>1);
        }
        }

        if (isset($_POST['e']) && $_POST['e']=='1')
        {
        $_SESSION['cart'] =;
        }

        echo '<br /><br />';
        print_r($_SESSION["cart"]);

        ?>
        <form action="cart2.php" method="post" enctype="application/x-www-form-urlencoded">
        MAST-O-MIR<br/>
        img<br/>
        £2.00<br/>
        <input type="hidden" value="1" name="prod" />
        <input type="hidden" value="MAST-O-MIR" name="name" />
        <button class="plus-btn" type="Submit">Add</button>
        </form>
        <form action="cart2.php" method="post" enctype="application/x-www-form-urlencoded">
        MAST-O-MIR<br/>
        img<br/>
        £2.00<br/>
        <input type="hidden" value="2" name="prod" />
        <input type="hidden" value="MAST-OMIR" name="name" />
        <button class="plus-btn" type="Submit">Add</button>
        </form>






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 28 '18 at 18:54









        KurohigeKurohige

        6001621




        6001621

























            0














            It's hard to test your code without a sample form but I guess both of your problems may be solved by replacing:



            $_SESSION["cart"][0] = array($_POST["prod"], $_POST["name"], $_SESSION["cart"][0][2]+1);


            For:



            $_SESSION["cart"][0][2]+= 1;


            By the way, try to properly indent your code when you are going to post it. It is hard to read.






            share|improve this answer
























            • Thanks Cool Guy, I've added the sample form as you suggested and in the meantime I'll give this a go

              – Simon
              Nov 28 '18 at 14:43











            • This doesn't work, after adding the first items and then clicking "add" for the second it just stops processing and then I can't see any of my basket or items on the screen until I reset the array

              – Simon
              Nov 28 '18 at 16:25
















            0














            It's hard to test your code without a sample form but I guess both of your problems may be solved by replacing:



            $_SESSION["cart"][0] = array($_POST["prod"], $_POST["name"], $_SESSION["cart"][0][2]+1);


            For:



            $_SESSION["cart"][0][2]+= 1;


            By the way, try to properly indent your code when you are going to post it. It is hard to read.






            share|improve this answer
























            • Thanks Cool Guy, I've added the sample form as you suggested and in the meantime I'll give this a go

              – Simon
              Nov 28 '18 at 14:43











            • This doesn't work, after adding the first items and then clicking "add" for the second it just stops processing and then I can't see any of my basket or items on the screen until I reset the array

              – Simon
              Nov 28 '18 at 16:25














            0












            0








            0







            It's hard to test your code without a sample form but I guess both of your problems may be solved by replacing:



            $_SESSION["cart"][0] = array($_POST["prod"], $_POST["name"], $_SESSION["cart"][0][2]+1);


            For:



            $_SESSION["cart"][0][2]+= 1;


            By the way, try to properly indent your code when you are going to post it. It is hard to read.






            share|improve this answer













            It's hard to test your code without a sample form but I guess both of your problems may be solved by replacing:



            $_SESSION["cart"][0] = array($_POST["prod"], $_POST["name"], $_SESSION["cart"][0][2]+1);


            For:



            $_SESSION["cart"][0][2]+= 1;


            By the way, try to properly indent your code when you are going to post it. It is hard to read.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 28 '18 at 14:06









            Cool GuyCool Guy

            318




            318













            • Thanks Cool Guy, I've added the sample form as you suggested and in the meantime I'll give this a go

              – Simon
              Nov 28 '18 at 14:43











            • This doesn't work, after adding the first items and then clicking "add" for the second it just stops processing and then I can't see any of my basket or items on the screen until I reset the array

              – Simon
              Nov 28 '18 at 16:25



















            • Thanks Cool Guy, I've added the sample form as you suggested and in the meantime I'll give this a go

              – Simon
              Nov 28 '18 at 14:43











            • This doesn't work, after adding the first items and then clicking "add" for the second it just stops processing and then I can't see any of my basket or items on the screen until I reset the array

              – Simon
              Nov 28 '18 at 16:25

















            Thanks Cool Guy, I've added the sample form as you suggested and in the meantime I'll give this a go

            – Simon
            Nov 28 '18 at 14:43





            Thanks Cool Guy, I've added the sample form as you suggested and in the meantime I'll give this a go

            – Simon
            Nov 28 '18 at 14:43













            This doesn't work, after adding the first items and then clicking "add" for the second it just stops processing and then I can't see any of my basket or items on the screen until I reset the array

            – Simon
            Nov 28 '18 at 16:25





            This doesn't work, after adding the first items and then clicking "add" for the second it just stops processing and then I can't see any of my basket or items on the screen until I reset the array

            – Simon
            Nov 28 '18 at 16:25


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53520086%2fupdating-a-specific-key-within-a-multidimensional-array-php%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Lallio

            Futebolista

            Jornalista