views:

690

answers:

4

How can I do the following without lots of complicated code?

  1. Explode each value of an array in PHP (I sort of know how to do this step)
  2. Discard the first part
  3. Keep the original key for the second part (I know there will be only two parts)

By this, I mean the following:

$array[1]=blue,green
$array[2]=yellow,red

becomes

$array[1]=green //it exploded [1] into blue and green and discarded blue
$array[2]=red // it exploded [2] into yellow and red and discarded yellow

I just realized, could I do this with a for...each loop? If so, just reply yes. I can code it once I know where to start.

+1  A: 

Try this:

$arr = explode(',','a,b,c');
unset($arr[0]);

Although, really, what you're asking doesn't make sense. If you know there are two parts, you probably want something closer to this:

list(,$what_i_want) = explode('|','A|B',2);
Mark
This answer doesn't make so much sense after the edit :\
Mark
A: 
foreach ($array as $k => &$v) {
    $v = (array) explode(',', $v);
    $v = (!empty($v[1])) ? $v[1] : $v[0];
}
cballou
I was about to suggest `array_shift` too, but the doc says it will renumber your keys (if they're numeric). Exploding generates numeric keys.
Mark
+4  A: 

given this:

$array[1] = "blue,green";
$array[2] = "yellow,red";

Here's how to do it:

foreach ($array as $key => $value) {
    $temp = explode(",", $value, 2);  // makes sure there's only 2 parts
    $array[$key] = $temp[1];
}

Another way you could do it would be like this:

foreach ($array as $key => $value) {
    $array[$key] = preg_replace("/^.+?,$/", "", $value);
}

... or use a combination of substr() and strpos()

nickf
or `list(,$array[$key]) = explode(',',$value,2);`
Mark
A: 

The array you start with:

$array[1] = "blue,green";
$array[2] = "yellow,red";

One way of coding it:

function reduction($values)
{
    // Assumes the last part is what you want (regardless of how many you have.)
    return array_pop(explode(",", $values));
}

$prime = array_map('reduction', $array);

Note: This creates a different array than $array.

Therefore $array == $prime but is not $array === $prime

null