Can you delete from an array?

Discussion in 'PHP' started by Greenmethod, Oct 18, 2007.

  1. #1
    I am in the process of making a shopping cart for my website, and have each item in the cart as a multidimensional array. One of the elements in it is 'ordered', which has the quantity being ordered. Is there any way to delete the array element if the quantity ordered is 0? Thanks in advance!
     
    Greenmethod, Oct 18, 2007 IP
  2. ste.richards

    ste.richards Guest

    Messages:
    46
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    You can use the unset() function.
     
    ste.richards, Oct 18, 2007 IP
  3. wmtips

    wmtips Well-Known Member

    Messages:
    601
    Likes Received:
    70
    Best Answers:
    1
    Trophy Points:
    150
    #3
    You can use array_splice function to remove elements from array.
     
    wmtips, Oct 18, 2007 IP
  4. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #4
    In your case I would use the unset option.

    unset($array['ordered']);
     
    jestep, Oct 18, 2007 IP
  5. Danltn

    Danltn Well-Known Member

    Messages:
    679
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    120
    #5
    function array_del($str,&$array)
    {
    // Remove a variable from an array. Example usage: array_del($str,$array);
        if (in_array($str,$array)==true)
        {
       
            foreach ($array as $key=>$value)
            {
       if ($value==$str) unset($array[$key]);
            }
        }
    }     
    PHP:
    Not sure if it's what you wanted
     
    Danltn, Oct 19, 2007 IP
  6. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #6
    A slightly faster way to do the same as above would be:
    
    function del_array($str, array &$array)
    {
    	if (($key = array_search($str, $array)) !== false)
    	{
    		unset($array[$key]);
    	}
    }
    
    PHP:
     
    nico_swd, Oct 19, 2007 IP