0

I just tried to parse my array that contains numbers separated with comma into numbers without the comma, but still in array form. But it didn't work.

My code:

$total = $this->input->post('total');
$arrTot = array_filter(array_slice($total, 20));
print_r($arrTot);

Array result:

Array
(
   [0] => 10,000
   [1] => 100,000
   [2] => 200,000
)

My desired output was to erase the comma in all number:

Array
(
    [0] => 10000
    [1] => 100000
    [2] => 200000
)

I've tried with something just like this but it seems not even close with my desired output:

$total = $this->input->post('total');
$arrTot = array_filter(array_slice($total, 20));
for ($i=0; $i < count($arrTot); $i++) { 
    $valTot=str_replace( ',', '', $arrTot[$i]);
    print_r($valTot);
}

Is there any way to solve this problem?

Thanks.

6 Answers 6

2

You can use array_walk to process each of the values in the array:

$arrTot = array('10,000', '100,000', '200,000');
array_walk($arrTot, function (&$v) {
    $v = str_replace(',', '', $v);
});
print_r($arrTot);

Output:

Array
(
    [0] => 10000
    [1] => 100000
    [2] => 200000
)

Demo on 3v4l.org

Sign up to request clarification or add additional context in comments.

2 Comments

Damn it! I don't even know that there is array_walk, thanks man you save ma day.
@baimWonk it's just a shorthand way of writing the loop you already had. All the other answers show how to fix your existing code.
1

you might assign new value to current variable.

$arrTot = array_filter(array_slice($total, 20));
for ($i=0; $i < count($arrTot); $i++) { 
    $arrTot[$i]=str_replace( ',', '', $arrTot[$i]);
}
print_r($arrTot);

Comments

0

If you want the desired output, you need to replace the elements in the main array without comma.

$total = $this->input->post('total');
$arrTot = array_filter(array_slice($total, 20));

foreach ($arrTot as $key => $aTot) {
    $arrTot[$key] = str_replace(',','',$arrTot[$i);
}
var_dump($arrTot);

Comments

0

Try this-

echo "<pre>";
$arr = array('10,000','100,000','200,000');
print_r($arr);
//result 
   Array
  (
      [0] => 10,000
      [1] => 100,000
      [2] => 200,000
  )
foreach ($arr as $key => $value) {
   $new[] = str_replace(',','',$value);
}
print_r($new);
Array
(
    [0] => 10000
    [1] => 100000
    [2] => 200000
)

Comments

0

try this ,

$arr = ['10,000','100,000','200,000'];
foreach($arr as $key=>$val){
  $arr[$key] = (int)str_replace(',','',$val);
}

var_dump($arr);

Comments

0

You could simply use str_replace to achieve desired result

$arrTot = array('10,000', '100,000', '200,000');

foreach($arrTot as $key => $value){
  $arrTot[$key] = str_replace(",","",$value);
}

print_r($arrTot);

Comments

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.