开发者

PHP output of foreach loop into a new array

开发者 https://www.devze.com 2022-12-24 04:19 出处:网络
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.

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开发者_JS百科 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.


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];
}


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

精彩评论

暂无评论...
验证码 换一张
取 消