What is the best method to remove commas from numbers in the associative array below? Keep the commas in text, thanks.
$main_arr contains the following 3 arrays:
Array
(
[phrase] => Hi, I'm ok
[number_a] => 3,575
[number_b] => 64
[number_c] => 8,075
)
Array
(
[phrase] => Bye, it's late
[number_a] => 7,365
[number_b] => 32
[number_c] => 648,120
)
Array
(
[phrase] => Good catch!
[number_a] => 11,659
[number_b] => 128
[number_c] => 1,492,352
CodePudding user response:
<?php
$mainArray =[
[
'phrase' => "Hi, I'm ok",
'number_a' => "3,575",
'number_b' => "64",
'number_c' => "8,075",
],
[
'phrase' => "Bye, it's late",
'number_a' => "7,365",
'number_b' => "32",
'number_c' => "648,120",
],
[
'phrase' => 'Good catch!',
'number_a' => "11,659",
'number_b' => "128",
'number_c' => "1,492,352",
],
];
foreach($mainArray as &$array) {
foreach($array as &$val) {
if (preg_match('/^[0-9,]*$/', $val)){
$val = str_replace(',','',$val);
}
}
}
var_export($mainArray);