Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 20
  1. #1
    Regular Coder
    Join Date
    Jan 2008
    Location
    Geneva, Switzerland
    Posts
    413
    Thanks
    12
    Thanked 29 Times in 29 Posts

    Remove value from array

    Hi folks,

    I have an array that is stored in a session var. The array contains user IDs.

    PHP Code:
    print_r ($_SESSION['recipientId']);
    // Array ( [0] => 24 [1] => 250 [2] => 220 [3] => 210 [4] => 241 [5] => 428 ) 
    How would I do to remove the ID '250' from the array? (Not the first or last one or any fixed position. Can be any value, but only one at a time.)

    I have tried unset, but that doesn't seem to work, or I am doing something wrong.

    TIA!
    Chuck Norris counted to infinity.
    Twice.

  • #2
    Senior Coder djm0219's Avatar
    Join Date
    Aug 2003
    Location
    Wake Forest, North Carolina
    Posts
    1,304
    Thanks
    4
    Thanked 204 Times in 201 Posts
    unset is the way to do it. You'll need to know the key to the element in the array that you want to remove of course. In your example that would be 1 so unset would be:

    PHP Code:
    unset($_SESSION['recipientId'][1]); 
    Dave .... HostMonster for all of your hosting needs

  • #3
    Regular Coder
    Join Date
    Jan 2008
    Location
    Geneva, Switzerland
    Posts
    413
    Thanks
    12
    Thanked 29 Times in 29 Posts
    Yes, but I can't do that I think, I'd like to remove by value. Or then I'd need to search for the key first?
    Chuck Norris counted to infinity.
    Twice.

  • #4
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    I don't think PHP has a way to return a key for a value.
    There are a few solutions though, the first is a simple iteration:
    PHP Code:
    $toRemove 250;
    reset($_SESSION['recipientId']);
    while (
    $current current($_SESSION['recipientId']))
    {
        if (
    $current == $toRemove)
        {
            unset(
    $_SESSION['recipientId'][key($current)]);
            break;
        }
        
    next($_SESSION['recipientId']);

    That should work. Another option is to flip you're key/value combinations and unset. That should also work, though you'll need to copy back into the $_SESSION superglobal since it doesn't work on a reference:
    PHP Code:
    $toRemove 250;
    $aRemoveFrom array_flip($_SESSION['recipientId']);
    unset(
    $aRemoveFrom[$toRemove]); // This will need error checking since we don't know if offset $toRemove exists in $aRemoveFrom
    $_SESSION['recipientId'] = $aRemoveFrom
    That should work too methinks.
    I assumed in both situations that the 250 represents a unique value within the array.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 
    Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)

  • Users who have thanked Fou-Lu for this post:

    Arnaud (09-08-2009)

  • #5
    Regular Coder
    Join Date
    Jan 2008
    Location
    Geneva, Switzerland
    Posts
    413
    Thanks
    12
    Thanked 29 Times in 29 Posts
    Thank you. I will try that.

    Quick question though. I was thinking about passing the userId as the array key and the userNames as the corresponding values (I am using two arrays right now, which I think is not the best solution).

    Unsetting the key would unset the associated value, right?
    Chuck Norris counted to infinity.
    Twice.

  • #6
    Senior Coder kbluhm's Avatar
    Join Date
    Apr 2007
    Location
    Philadelphia, PA, USA
    Posts
    1,509
    Thanks
    3
    Thanked 258 Times in 254 Posts
    That is correct.

    Here is a bit more elegant solution to your current setup:
    PHP Code:
    $userId 250;

    if ( 
    FALSE !== ( $key array_search$userId$_SESSION['recipientId'] ) ) )
    {
        unset( 
    $_SESSION['recipientId'][$key] );

    If you plan to use the user ID as the array key:
    PHP Code:
    $userId 250;

    if ( isset( 
    $_SESSION['recipientId'][$userId] ) )
    {
        unset( 
    $_SESSION['recipientId'][$userId] );


  • Users who have thanked kbluhm for this post:

    Arnaud (09-08-2009)

  • #7
    Regular Coder
    Join Date
    Jan 2008
    Location
    Geneva, Switzerland
    Posts
    413
    Thanks
    12
    Thanked 29 Times in 29 Posts
    Got it all sorted now. Thank you guys for your help.

    Now passing userIds and userNames as array keys and values. Passing the whole array into a session and then listing what I need (values for display and keys for further calculations) using:

    PHP Code:
    <?
    foreach ($_SESSION['recipient'] as $thevalues) {
      
    $thekeys array_search($thevalues$_SESSION['recipient']);
      echo 
    "<a class='medium' href='index.php?page=members/mail.php&action=remove&removeId="$thekeys ."'>" $thevalues "</a>; ";
    }
    ?>
    Then using Kbluhm solution for unsetting:

    PHP Code:
    <?
    if ($action == "remove") {
       if (isset(
    $_SESSION['recipient'][$removeId])) {
          unset(
    $_SESSION['recipient'][$removeId]);
       }
    }
    ?>
    Last question though... do I really need to use that isset line? I guess the answer is yes and no. Is it just safer?
    Chuck Norris counted to infinity.
    Twice.

  • #8
    Senior Coder kbluhm's Avatar
    Join Date
    Apr 2007
    Location
    Philadelphia, PA, USA
    Posts
    1,509
    Thanks
    3
    Thanked 258 Times in 254 Posts
    It will save a notice being thrown if the key does not exist. I don't know how you're retrieving the value to be removed, but when removing values from an array, it is good practice to make sure it exists before you remove it... juuust in case.

  • #9
    Regular Coder
    Join Date
    Jan 2008
    Location
    Geneva, Switzerland
    Posts
    413
    Thanks
    12
    Thanked 29 Times in 29 Posts
    Okay I see the point. In that specific case, I cannot request an element to be removed if it is not in the array, since each key and value is unique and I actually display the contents of the array with a link for each element to remove it.

    Now I have 1 more question

    I want to be able to ADD more elements to the array that is stored in a session.
    So, basically, if the session array is already set, add values (merge with the $_POST array), otherwise, simply set it.

    PHP Code:
    <?
    if ($_POST['action'] == "addrecipients") {
      if (isset(
    $_SESSION['recipient'])) {
        
    $_SESSION['recipient'] = array_merge($_SESSION['recipient'], $_POST['recipient']);
      } else {
        
    $_SESSION['recipient'] = $_POST['recipient'];
      }
    }
    ?>
    This works... but, I seem to be losing the keys.

    When I simply set it, I get something like:

    Array ( [115] => user1 [54] => user2 [199] => user3 [12] => user4 )

    After a merge, it looks like that:

    Array ( [0] => user1 [1] => user2 [2] => user3 [3] => user4 [4] => user5 )

    Any idea how I could achieve a merge while still keeping the defined keys?

    TIA!!
    Last edited by Arnaud; 09-08-2009 at 03:33 PM.
    Chuck Norris counted to infinity.
    Twice.

  • #10
    Senior Coder kbluhm's Avatar
    Join Date
    Apr 2007
    Location
    Philadelphia, PA, USA
    Posts
    1,509
    Thanks
    3
    Thanked 258 Times in 254 Posts
    What is the value of $_POST['recipient'] when you run it through var_dump()? It must be an array, so better check first thing if we're going to get this figured out.
    PHP Code:
    if ($_POST['action'] == "addrecipients") {
      
    var_dump$_POST['recipient'] );
      exit;

    Last edited by kbluhm; 09-08-2009 at 03:49 PM.

  • #11
    Regular Coder
    Join Date
    Jan 2008
    Location
    Geneva, Switzerland
    Posts
    413
    Thanks
    12
    Thanked 29 Times in 29 Posts
    Ok... one example with the real IDs and UserNames through var_dump();

    array(9) { [405]=> string(10) "manager-49" [317]=> string(4) "mawa" [304]=> string(10) "McRodolphe" [26]=> string(7) "Micky90" [97]=> string(8) "mimoroyo" [225]=> string(5) "minux" [205]=> string(5) "misko" [381]=> string(7) "Muzzo78" [276]=> string(6) "Myst01" }
    Chuck Norris counted to infinity.
    Twice.

  • #12
    Senior Coder kbluhm's Avatar
    Join Date
    Apr 2007
    Location
    Philadelphia, PA, USA
    Posts
    1,509
    Thanks
    3
    Thanked 258 Times in 254 Posts
    I was talking about the value you're attempting to insert. The value of $_POST['recipient']

  • #13
    Regular Coder
    Join Date
    Jan 2008
    Location
    Geneva, Switzerland
    Posts
    413
    Thanks
    12
    Thanked 29 Times in 29 Posts
    Ok... not sure I understand your question but...

    Yes... what I posted before is the value of $_POST['recipient']...

    $_POST['recipient'] is a form submit that I turned into an array, passing the userIDs as keys and userNames as values. Then on the form action page, I store the array into a session var. Now when I repeat the operation, I do not want to replace the content of the session var (array) if it already contains something. I want the POST array to be added, or merged, with the SESSION array.

    Hope this is clearer
    Chuck Norris counted to infinity.
    Twice.

  • #14
    Regular Coder
    Join Date
    Jan 2008
    Location
    Geneva, Switzerland
    Posts
    413
    Thanks
    12
    Thanked 29 Times in 29 Posts
    Ok, forget it...

    I didn't realize that I could just do the following...

    PHP Code:
    <?
    if ($_POST['action'] == "addrecipients") {
      if (isset(
    $_SESSION['recipient'])) {
        
    $_SESSION['recipient'] = $_SESSION['recipient'] + $_POST['recipient'];
      } else {
        
    $_SESSION['recipient'] = $_POST['recipient'];
      }
    }
    ?>
    Everything sorted out now.
    until the next issue...

    Thanks!
    Chuck Norris counted to infinity.
    Twice.

  • #15
    Regular Coder
    Join Date
    Apr 2008
    Posts
    685
    Thanks
    15
    Thanked 105 Times in 104 Posts
    Or even smaller without the curly braces
    ..and use of the += to summarise something equaling the same thing plus something else

    PHP Code:
    <?
    if ($_POST['action'] == "addrecipients"){ 
      if (isset(
    $_SESSION['recipient'])) $_SESSION['recipient'] += $_POST['recipient'];
      else 
    $_SESSION['recipient'] = $_POST['recipient'];
    }
    ?>


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

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