PDA

View Full Version : How do I explode, do something, implode?


JJR512
07-20-2002, 12:26 AM
Let's say I have an array:

$array = "50,60,70,80,90";

And I want to take each element of the array and do something with it. The specific something is a mathmatical operation; let's say I want to subtract 10 from each number. Then, after subracting 10 from each number, I want so put all the results back into a new array. The new array would look like "40,50,60,70,80".

How do I write this?

I know to start with something like:

$exploded_array = explode(",",$array)

But where do I go from there? (And in the explode(), does $array need to be enclosed in quotes or not?)

Admin
07-20-2002, 07:16 AM
function subtract(&$value) {
$value -= 10;
}

$string = '50,60,70,80,90';
$array = explode(',', $string);
array_walk($array, 'subtract');
$string = implode(',', $array);

You can also use foreach, like this:
$string = '50,60,70,80,90';
$array = explode(',', $string);
foreach ($array as $key => $value) {
$array[$key] -= 10;
}
$string = implode(',', $array);
But I think the first method is more elegant. :)

Neo
07-20-2002, 07:24 AM
Chen I forget but why do you add a & to the front of a variable in certain cases?

JJR512
07-20-2002, 07:28 AM
Thanks!

Admin
07-20-2002, 07:54 AM
Originally posted by Neo
Chen I forget but why do you add a & to the front of a variable in certain cases?
I can't explain the whole thing in a post, read this:
http://php.fastmirror.com/manual/en/language.references.php

Neo
07-20-2002, 09:25 AM
Thanks for the help as always.