0

I have an array ($arr):

[0] => Array
    (
        [sv_317] => 1,650
        [sv_318] => 1,254

    )


[1] => Array
    (
        [sv_317] => 1,580
        [sv_318] => 1,580

    )

I am trying to use these element values as number values and so need to remove any non numeric characters (commas in the above example).

To do this I am using:

foreach($arr as $k=>$v)
    {       
    $v[sv_317] = str_replace(",", "", $v[sv_317]);
    $v[sv_317] = preg_replace('/\s+/', '', $v[sv_317]);
    $v[sv_318] = str_replace(",", "", $v[sv_318]);
    $v[sv_318] = preg_replace('/\s+/', '', $v[sv_318]);

    echo "318 :".$v[sv_318];
    echo "317 :".$v[sv_317];
    }

The echos are there just to test that it is doing what I intended, and sure enough they print the values of the elements without commas or white-space.

However this didn't result in being able to use the elements numerically, so I tested the array with print_r($arr); immediately following the above loop, and the array elements appeared unaffected (i.e. still containing commas.

Is there an issue of scope here? If so how can I remove the commas permanently?

Many thanks.

Gideon
  • 1,878
  • 4
  • 40
  • 71

2 Answers2

2

Since you're trying to change $v, it needs to be a reference variable, like this:

foreach($arr as $k => &$v) {       
  $v[sv_318] = str_replace(",", "", $v[sv_318]);
}

...But there is more to fix in your code:

  • You should unset($v) at the end, so subsequent code doesn't act strangely
  • The array indexes should be quoted, since they are string literals.
  • I prefer strtr() to str_replace(), since the correspondence is clearer:

.

foreach($arr as $k => &$v) {
  $v['sv_318'] = strtr( $v['sv_318'], array(','=>'') );
}; unset($v);

Also, to handle any number of values in $v, I'd use another foreach:

foreach ($arr as $key => &$subarr) {       
  foreach ($subarr as $subkey => &$val) {       
    $val = strtr( $val, array(','=>'') );
  }; unset($val);
}; unset($subarr);
wst
  • 21
  • 2
1

The foreach loop doesn't work with the array itself. It works with a copy of the array. So, when you do print_r($arr) it's displaying the original array. The actual array $arr is not modified.

From PHP foreach documentation:

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>

Check this SO post to understand how foreach actually works: How does PHP 'foreach' actually work?

Hope this answers your question :)

Community
  • 1
  • 1
Amal Murali
  • 75,622
  • 18
  • 128
  • 150