March 10, 2012

How to handle my data?

Question by Jack4

Edit: The aim of my method is to delete a value from a string in a database.

I cant seem to find the answer for this one anywhere. Can you concatenate inside a str_replace like this:

str_replace($pid . ",","",$boom);
  • $pid is a page id, eg 40
  • $boom is an exploded array

If i have a string: 40,56,12 i want to make it 56,12 however without the concatenator in it will produce:

,56,12

When i have the concat in the str_replace it doesnt do a thing. So does anyone know if you can do this?

Answer by hakre

After you have edited it becomes clear that you want to remove the value of $pid from the array $boom which contains one number as a value. You can use array_search to find if it is in at if in with which key. You can then unset the element from $boom:

$pid = '40';
$boom = explode(',', '40,56,12');
$r = array_search($pid, $boom, FALSE);
if ($r !== FALSE) {
    unset($boom[$r]);
}

Old question:

Can you concatenate inside a str_replace like this: … ?

Yes you can, see the example:

$pid = '40';
$boom = array('40,56,12');
print_r(str_replace($pid . ",", "", $boom));

Result:

Array
(
    [0] => 56,12
)

Which is pretty much like you did so you might be looking for the problem at the wrong place. You can use any string expression for the parameter.

It might be easier for you if you’re unsure to create a variable first:

$pid = '40';
$boom = array('40,56,12');
$search = sprintf("%d,", $pid);
print_r(str_replace($search, "", $boom));

Answer by Starx

As $boom is an array, you don’t need to use array on your case.

Change this

$boom = explode(",",$ticket_array);
$boom = str_replace($pid . ",","",$boom);
$together = implode(",",$boom);

to

$together = str_replace($pid . ",","",$ticket_array);

Update: If you want still want to use array

$boom = explode(",",$ticket_array);
unset($boom[array_search($pid, $boom)]);
$together = implode(",",$boom);

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!