Jump to content

Moving value from named key up when previous is empty in associative array


Recommended Posts

I have an array of data where a user can delete names and their value, like below. This is what the array looks like after a couple are deleted:

    [0] => Array
        [name1] => 
        [value1] => 
        [name2] => Name
        [value2] => 10
        [name3] => Another name
        [value3] => 20
        [name4] => 
        [value4] => 
        [name5] => And Another
        [value5] => 40

I need to dynamically move up the values if any are deleted, so the array becomes:

    [0] => Array
        [name1] => Name
        [value1] => 10
        [name2] => Another name
        [value2] => 20
        [name3] => And Another
        [value3] => 40
        [name4] => 
        [value4] => 
        [name5] => 
        [value5] => 

I need to keep all named keys in the array too. Has anyone ran across this problem?

Link to comment
Share on other sites

if you review your previous thread on the forum ( http://forums.phpfreaks.com/topic/279439-simple-shopping-cart/ ), where you were using array indexes with sequential numerical endings, the same as what you are doing now, someone suggested a simplified approach that reduced the amount of code to almost nothing.


you need to define a data structure that supports what you are doing, not make it harder. i'm betting if you use the same approach that was suggested in that previous thread, and use the name as the array index and the corresponding value as the array value, and just delete (unset()) the element(s) from the array, it will solve your problem.

Edited by mac_gyver
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.

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.