baimWonk
baimWonk

Reputation: 841

PHP: Array Convert comma separated string to int

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.

Upvotes: 0

Views: 175

Answers (6)

sn n
sn n

Reputation: 399

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

Upvotes: 0

Zar Ni Ko Ko
Zar Ni Ko Ko

Reputation: 352

try this ,

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

var_dump($arr);

Upvotes: 0

Anshu Sharma
Anshu Sharma

Reputation: 170

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
)

Upvotes: 0

William Prigol Lopes
William Prigol Lopes

Reputation: 1889

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

Upvotes: 0

Nick
Nick

Reputation: 147206

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

Upvotes: 2

Spy.Murad
Spy.Murad

Reputation: 51

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

Upvotes: 1

Related Questions