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.

1
  • Could you post your function? Commented Mar 28, 2010 at 4:36

2 Answers 2

3

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];
}
Sign up to request clarification or add additional context in comments.

Comments

1

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"
}

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.