views:

83

answers:

2

I know I'm probably missing something easy, but I have a foreach loop and I'm trying to modify the values of the first array, and output a new array with the modifications as the new values.

Basically I'm starting with an array: 0 => A:B 1 => B:C 2 => C:D

And I'm using explode() to strip out the :'s and second letters, so I want to be left with an array: 0 => A 1 => B 2 => C

The explode() part of my function works fine, but I only seem to get single string outputs. A, B, and C.

A: 

Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself

$arr = array( 0 => 'A:B', 1 => 'B:C', 2 => 'C:D');
// foreach($arr as $val) will not work.
foreach($arr as &$val) { // prefix $val with & to make it a reference to actual array values and not just copy a copy.
    $temp = explode(':',$val);
    $val = $temp[0];
}
var_dump($arr);

Output:

array(3) {
  [0]=>
  string(1) "A"
  [1]=>
  string(1) "B"
  [2]=>
  &string(1) "C"
}
codaddict
Hey, I tried your response too as it looks what I need to do also, but for some reason I couldn't get it to work... Not really sure why, it's not that complicated and it's already just about how mine is structured. Oh well, thanks anyway :)
RobHardgood
A: 

Sounds like you want something like this?

$initial = array('A:B', 'B:C', 'C:D');
$cleaned = array();
foreach( $initial as $data ) {
  $elements = explode(':', $data);
  $cleaned[] = $elements[0];
}
sobedai
Aha! Exactly what I needed. Thanks!
RobHardgood