SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Evangelist JordashTalon's Avatar
    Join Date
    Dec 2008
    Posts
    505
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    delete a number in a comma seperated string

    I have a string like this:

    12,18,4

    Let's say I want to delete the 18 out of the string so it's like this:

    12,4

    What would be a good way to do that?

    Also I need to do an add but only if the number is not already in the string,

    So I have

    12,18,4

    And I try to add 18

    it should fail because 18 is already there but if I try and add 9 it will add it on

    12,18,4,9 (I already got this part working)

  2. #2
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,042
    Mentioned
    16 Post(s)
    Tagged
    3 Thread(s)
    PHP Code:
    $nums '12,18,4';
    $s array_search(18,explode(',',$nums));
    if(
    $s!==false) unset($nums[$s]); 

  3. #3
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,042
    Mentioned
    16 Post(s)
    Tagged
    3 Thread(s)
    Probably how I would handle the second part.

    PHP Code:
    <?php
    $nums 
    '2,4,5,78,90';
    $add = array(2,4,5,6,7);
    $saved explode(',',$nums);
    $diff array_diff($add,$saved);
    if(!empty(
    $diff)) $saved array_merge($saved,$diff);
    $nums implode(',',$saved);
    echo 
    '<p>',$nums,'</p>';
    ?>

  4. #4
    SitePoint Evangelist JordashTalon's Avatar
    Join Date
    Dec 2008
    Posts
    505
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    thanks, that helped alot


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
  •