SitePoint Sponsor

User Tag List

Results 1 to 13 of 13
  1. #1
    midnight coder
    Join Date
    Dec 2000
    Location
    The flat edge of the world
    Posts
    838
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    How to delete something from an array?

    Say I have an array:

    $fruits = array('apple','orange','banana','strawberry');

    How do I delete $fruits[1] from the array to get rid of orange, so it's left with:

    $fruits = array('apple','banana','strawberry');

  2. #2
    Making a better wheel silver trophy DR_LaRRY_PEpPeR's Avatar
    Join Date
    Jul 2001
    Location
    Missouri
    Posts
    3,428
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    - Matt ** Ignore old signature for now... **
    Dr.BB - Highly optimized to be 2-3x faster than the "Big 3."
    "Do not enclose numeric values in quotes -- that is very non-standard and will only work on MySQL." - MattR

  3. #3
    midnight coder
    Join Date
    Dec 2000
    Location
    The flat edge of the world
    Posts
    838
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks, still got a wee bit of a problem, I have an array like:

    Array ( [0] => apple [1] => orange [2] => banana )

    After deleting orange, I get:

    Array ( [0] => apple [2] => banana )

    Is there a way to rearrange the numbers so they adjust themselves to

    Array ( [0] => apple [1] => banana )

  4. #4
    Making a better wheel silver trophy DR_LaRRY_PEpPeR's Avatar
    Join Date
    Jul 2001
    Location
    Missouri
    Posts
    3,428
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    hmm, i'm not very knowledge able about this but it seems like to fix that you might have to array_slice() the array into 2 pieces, around the element you want to delete. and then array_splice() the second one back onto the end of it. i have no idea if that'll reset the numbers though.

    EDIT: if you check the array_slice() function and look at the first user comment it says how to delete an element. and it looks like you'd put them together with array_merge(), not splice. still, i don't know if it resets the numbers, but try it out.
    Last edited by DR_LaRRY_PEpPeR; Aug 10, 2001 at 23:37.

  5. #5
    ********* Callithumpian silver trophy freakysid's Avatar
    Join Date
    Jun 2000
    Location
    Sydney, Australia
    Posts
    3,798
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I wrote a function for ya. Coming up with an algorithm was too much to resist. Sorry if the logic is a little kooky - that's just my brain Also, you can give it a better name than deleteShiftPop - but that is what it does!
    PHP Code:
    <?php
    /*************************************************************
     function deleteShiftPop
        receives: &$array - the address of $array
        receives: $x - the index of the element to remove
        returns: void (nothing)
    *************************************************************/    

    function deleteShiftPop(&$array$x) {
       
    // count the number of elements in the array
       
    $count count($array);
       
       
    // if $x is the last element the for loop will not be entered
       // but we still want to pop the last element
       // so toggle $pop to be true
       
    $pop = ($x == $count 1) ? true false;
       
       
    // starting at element x, shuffle each element down one
       
    for ( $x$x $count 1$x++ ) {
           
    $array[$x] = $array[$x+1];
           
    $pop true;
       }
       if (
    $pop) {
          
    array_pop($array);
       }
    }

    /*************************************************************/   
    // test code

    //$myArray = array('foo', 'bar', 'foobar', 'zoot', 'zog');
    $myArray = array(0,1,2,3,4,5,6,7,8,9,10);

    echo 
    '$myArray at start<br>';
       foreach(
    $myArray as $element) {
          echo 
    $element' ';
       }
       
    echo 
    '<br><br>lets test deleteShiftPop<br>';

    // lets delete loop through and delete the 3rd element each time
    while( count($myArray) > 2) {
       
    deleteShiftPop($myArray2);
       foreach(
    $myArray as $element) {
          echo 
    $element' ';
       }
       echo 
    '<br>';
    }
    ?>
    results:
    Code:
    $myArray at start
    0 1 2 3 4 5 6 7 8 9 10 
    lets test deleteShiftPop
    0 1 3 4 5 6 7 8 9 10 
    0 1 4 5 6 7 8 9 10 
    0 1 5 6 7 8 9 10 
    0 1 6 7 8 9 10 
    0 1 7 8 9 10 
    0 1 8 9 10 
    0 1 9 10 
    0 1 10 
    0 1
    Last edited by freakysid; Aug 11, 2001 at 03:19.

  6. #6
    SitePoint Evangelist
    Join Date
    Dec 2000
    Posts
    528
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This may seem like a stupid question, but what's the point of arrays?

    -Corbb
    Corbb O'Connor
    Looking for quality website design or database programming?
    Contact me for more information and a FREE quote!

  7. #7
    ********* Callithumpian silver trophy freakysid's Avatar
    Join Date
    Jun 2000
    Location
    Sydney, Australia
    Posts
    3,798
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    An array is a data structure. With a plain old variable you can only hold one value. Well what if you want to hold a set of values? That's where you use an array. Often you will use an array so that you can loop through a control structure like the foreach loop above and perform some common task on each element within the array. That is called traversing an array.

    For example. Lets say you want to add up a whole lot of numbers. You could do something like this:
    PHP Code:
    $n1 1;
    $n2 2;
    $n3 3;
    $n4 4;

    $total $n1 $n2 $n3 $n4
    But that is a bit cluncky. Also, the problem is that you have hard-coded in that there are only four variables that can be added together. However, if you had used an array, you can write one piece of code that will add all the elements together, even without knowing how many elements there will be in the array (the array data may be coming from user input POSTed from a form, or from a database table.
    PHP Code:
    // Here I hard code the array numbers but the array could be populated 
    // from data in a database table, etc.
    $numbers = array(1,2,3,4);

    foreach(
    $numbers AS $n) {
       
    $total += $n;

    In the second example above, the code will work regardless of whether there are 1 or 5 or 287 elements in the array (or even if the array is empty); that is, it will add up the total of all the elements in the array.

    Well that is just a very simple explaination. Arrays are increadibly usefull, and quite fundamental to programming in general. Thus you will find a wealth of written info/tutorials about arrays on the web. Enjoy!

  8. #8
    midnight coder
    Join Date
    Dec 2000
    Location
    The flat edge of the world
    Posts
    838
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks freaksid, the function seems to work fine, but not on my script!

    In my little testing script, it worked fine:

    PHP Code:
    $fruit = array('apple','orange','banana','strawberry','pear');

    print_r($fruit);

    deleteShiftPop($fruit3);

    print_r($fruit); 
    It gives the following which is perfect:

    Code:
    Array ( [0] => apple [1] => orange [2] => banana [3] => strawberry [4] => pear )
    
    Array ( [0] => apple [1] => orange [2] => strawberry [3] => pear )
    However, for some reason when I try this on my shopping cart script, the bit where a user clicks on "delete this item", it doesn't delete it from the multiple arrays stored in the session:

    PHP Code:
    session_start();

    //prints whats in the session's basket code array to start with
    print_r ($ses_basket_code);

        if (
    in_array($code,$ses_basket_code)) {
            
    // $int_key_position gives the key from the array of where the product is
            
    $int_key_position array_search($code,$ses_basket_code);
            
    // echoing it to make sure the number is correct, which it is
            
    echo "int_key_position: $int_key_position <br />";

            
    //delete from the arrays on where the product is
            
    deleteShiftPop($ses_baske_code$int_key_position);
            
    deleteShiftPop($ses_baske_name$int_key_position);
            
    deleteShiftPop($ses_baske_quantity$int_key_position);
            
    deleteShiftPop($ses_baske_price$int_key_position);
            
    deleteShiftPop($ses_baske_bsizeC$int_key_position);
            
    deleteShiftPop($ses_baske_weight$int_key_position);

            
    //print the basket code array again
            
    print_r ($ses_basket_code);
        } 
    For some reason, the things in the array doesn't get deleted, $ses_basket_code from before and after are identical, it didn't delete anything from it, and I can't figue out why...

  9. #9
    The Hiding One lynlimz's Avatar
    Join Date
    Jul 2000
    Location
    Singapore
    Posts
    2,103
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Originally posted by Corbb O'Connor
    This may seem like a stupid question, but what's the point of arrays?

    -Corbb
    Well...arrays are incredibly useful. Though I'm a rather beginner when using PHP, arrays have helped in organising data. especially when you have a huge script.

    Say for example, you cretae this list of names.
    PHP Code:
    $name_list = array("Lyon Lim" => '1',
                        
    "Weird"     => '1',
                        
    "Hello"      => '0',
    ); 
    the right column depicts whether this user should be displayed on the user listing page.

    you can then do something like:
    PHP Code:
    foreach ($name_list as $name => $show) {
        if (
    $show) { echo "$name\n"; }

    and the results would be like
    Code:
    Lyon Lim
    Weird
    you can also use these array multiple times throughout your script.
    did i just post a good example? hope i made some sense.
    "Imagination is more important than knowledge. Knowledge is limited. Imagination encircles the world."
    -- Albert Einstein

  10. #10
    :) delemtri's Avatar
    Join Date
    Jun 2001
    Posts
    579
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The neat thing about arrays is that you can use them to store individual pieces of related data and do things like loop through them.

  11. #11
    ********* Callithumpian silver trophy freakysid's Avatar
    Join Date
    Jun 2000
    Location
    Sydney, Australia
    Posts
    3,798
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I would be very curious to know whether this version of the function works on your session arrays:
    PHP Code:
    /*************************************************************
     function deleteShiftPop
        receives: $array
        receives: $x - the index of the element to remove
        returns: $array 
    *************************************************************/    

    function deleteShiftPop($array$x) {
       
    // count the number of elements in the array
       
    $count count($array);
       
       
    // if $x is the last element the for loop will not be entered
       // but we still want to pop the last element
       // so toggle $pop to be true
       
    $pop = ($x == $count 1) ? true false;
       
       
    // starting at element x, shuffle each element down one
       
    for ( $x$x $count 1$x++ ) {
           
    $array[$x] = $array[$x+1];
           
    $pop true;
       }
       if (
    $pop) {
          
    array_pop($array);
       }
       return 
    $array;

    In this case you would use it like so:
    PHP Code:
    $ses_baske_code deleteShiftPop($ses_baske_code,*$int_key_position);
    $ses_baske_name deleteShiftPop($ses_baske_name,*$int_key_position);
    ...
    etc... 
    If that works and my first yet my first version doesn't - then there is are issues with references in PHP and the symbol table, etc, that would be really interesting to know about and persue further. I have a hunch that the problem is this. $ses_baske_code, etc, are themselves references to elements in the array $HTTP_SESSION_VARS, that get created when register_globals is enabled in the ini file. So if you pass these by reference as I did in my first function deleteShiftPop(&$array, $x) then maybe referencing a reference to a value is going to break things down. If you have no idea of what I am talking about, don't worry neither do I. But I would be very interested to know if the second version of the function as given above works while the first did not.

    That all said, another approach to solving the problem you want to solve here might have been far simpler. I don't know how those session arrays are being used elsewhere in your application - but, there is a quick and dirty way of deleting an element in an array without actually deleting it. You mark it as deleted. Often in programming it is logical within the bounds of the business rules being applied to use a value of -1 to flag that a variable is uninitialised or marked as deleted and therefor should be ignored.

    So to flag an element as being deleted you could write:
    PHP Code:
    $ses_baske_code[$int_key_position] = -1;
    $ses_baske_name[$int_key_position] = -1;
    ...
    etc... 
    However, if you used this method, and you wanted to do something like add up the total price of the order, you would have to first test each element to see that it did not equal -1 before adding it onto the total price.

  12. #12
    midnight coder
    Join Date
    Dec 2000
    Location
    The flat edge of the world
    Posts
    838
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the help, unfortunately the function is still not quite right...

    The new function ended up emptying the array, after applying deleteShiftPop, print_r prints out nothing, and the cart doesn't show up any items at all...

  13. #13
    Dumb PHP codin' cat
    Join Date
    Aug 2000
    Location
    San Diego, CA
    Posts
    5,460
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If you are looking to just remove an element from an array and you know the number of the element you which to remove you could use this:

    PHP Code:
    <?
            
    function delElement($array) {
                global 
    $extractor;
                return 
    array_merge(array_slice($array,0,$extractor),
            
    array_slice($array,$extractor 1));
                }


        
    //the number of the element
        
    $extractor 3;


        
    $array = array("foo""foo1""foo2""foo3");
    ?>
    Before Extraction:
    <br>
    <?
        
    foreach($array as $key => $name) {
            print 
    "$key = $name<br>";
            }
    ?>

    After Extraction:
    <br>
    <?
        $array 
    delElement($array);

        foreach(
    $array as $key => $name) {
            print 
    "$key = $name<br>";
            }
    ?>
    Please don't PM me with questions.
    Use the forums, that is what they are here for.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •