Forum Moderators: coopster

Message Too Old, No Replies

Removing array element - Please help.

         

john551

6:50 am on Jan 3, 2006 (gmt 0)

10+ Year Member



I have stored some data in a single string seperated by comma.
Example:

$data="john,hari,gupta";
Now I want to remove hari from the $data and form the string as
$data="john,gupta";

I have exploded the data using explode function.
explode(',',$data);
But I dont no how to remove the element and form the string as shown in the example above. Please help

jc_armor

6:54 am on Jan 3, 2006 (gmt 0)

10+ Year Member



if your goal is to remove ",hari" from the string, you can just issue a str_replace command to remove it:

$data = str_replace(",hari","",$data);

john551

7:00 am on Jan 3, 2006 (gmt 0)

10+ Year Member



this was an example in above post.
The data string is dyanmically fetched from mysql.

The data could be anyhing like
$data="john,peter,dsa,weer,syz";

Now how have a form where I post say john, it should delete 'john' and form the string as
$data="peter,dsa,weer,syz";

If I use str_replace(',john', '', $data) it would'nt work. So any other way

hughie

10:14 am on Jan 3, 2006 (gmt 0)

10+ Year Member



If your are using explode then this would work

$data="john,hari,gupta";
$array=explode(",",$data);
foreach($array as $key=>$value)
{
if ($value=='john')
{
unset($array[$key]);
}
}

sort($array); // If you want to re order it

Rebrandt

12:43 pm on Jan 3, 2006 (gmt 0)

10+ Year Member



Slight modification:

<?php
$data= "john,hari,gupta";
$item = "hari";
$tmp = explode(",", $data);
unset($tmp[array_search($item, $tmp)]);
$data = implode(",", $tmp);
?>