SitePoint Sponsor |
|
User Tag List
Results 1 to 4 of 4
-
Apr 24, 2009, 13:40 #1
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)
-
Apr 24, 2009, 14:14 #2
- Join Date
- Jul 2006
- Location
- Augusta, Georgia, United States
- Posts
- 4,194
- Mentioned
- 17 Post(s)
- Tagged
- 5 Thread(s)
PHP Code:$nums = '12,18,4';
$s = array_search(18,explode(',',$nums));
if($s!==false) unset($nums[$s]);
-
Apr 24, 2009, 14:23 #3
- Join Date
- Jul 2006
- Location
- Augusta, Georgia, United States
- Posts
- 4,194
- Mentioned
- 17 Post(s)
- Tagged
- 5 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>';
?>
-
Apr 24, 2009, 14:28 #4
thanks, that helped alot
Bookmarks