waiwai933
waiwai933

Reputation: 14579

Exploding Arrays in PHP While Keeping the Original Key

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.

Upvotes: 1

Views: 3032

Answers (4)

nickf
nickf

Reputation: 546303

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()

Upvotes: 4

null
null

Reputation: 7594

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

Upvotes: 0

Corey Ballou
Corey Ballou

Reputation: 43507

foreach ($array as $k => &$v) {
    $v = (array) explode(',', $v);
    $v = (!empty($v[1])) ? $v[1] : $v[0];
}

Upvotes: 0

mpen
mpen

Reputation: 283133

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);

Upvotes: 1

Related Questions