Remove Commas From Numbers

I need to remove commas from numbers and I cant find the function that does this. I know I have used it before Somewhere but I cant remember.

$number = 45,900;

somefunction($number); // output: 45900

Thanks for your help.

str_replace(“,”, “”, $number)

Thank You. WOrks Great

Thumbs up :agree:

Guys,

str_replace() works not as expected for me.

$bad_symbols = array(",", ".");
$value = str_replace($bad_symbols, "", $value);

Everything after comma or decimal point in $value gets removed, so that “23.45” and “23,45” become “23”. I need them to become “2345”.

What am I doing wrong?
Thanks!
Algirdas

hi Algirdas,
Welcome to the forums!

When I run your code it gives me the expected result:


<?php
$value='23.45';
$bad_symbols = array(",", ".");
$value = str_replace($bad_symbols, "", $value);


echo $value;
?>

outputs:


2345

How do you get your $value ?

Cheers

Spike

Hey!
Thanks for a prompt reply!

Well, I’m trying to check if the user entered an integer. First, the data is received from the following form:

echo "<table><form name=\\"IS\\" action=\\"insert.php?id=2\\" method=\\"post\\">\
";					//load stored data in the table
echo "<tr><td>Revenues:</td><td><input type=\\"text\\" name=\\"revenues\\" value=\\"".$row['revenues']."\\"></td></tr>\
";
...
echo "<tr><td><input type=\\"submit\\" value=\\"Update\\"></td></tr>\
";
echo "</form></table>\
";

Then the submitted data is checked:

if (isset($_POST['revenues']) || isset($_POST['cogs']) || isset($_POST['ebitda']) || isset($_POST['ebit']) || isset($_POST['ebt']) || isset($_POST['net_income']))			//if any data has been submitted

foreach ($_POST as $value)
{
   $bad_symbols = array(",", ".");
   $value = str_replace($bad_symbols, "", $value);
   if (!empty($value) && $value !== strval(intval($value)))
      $error[$i++] = $value;
}

The comma/point is not registered as an error if I use str_replace(), so the data is entered into the database:

$query = "UPDATE `financials` SET revenues='".$_POST['revenues']."', cogs='".$_POST['cogs']."', ebitda='".$_POST['ebitda']."', ebit='".$_POST['ebit']."', ebt='".$_POST['ebt']."', net_income='".$_POST['net_income']."' WHERE company_id='".$_SESSION['company_id']."' AND term_id='".$_SESSION['term_id']."'";
$result = mysql_query($query) or die ("&lt;p class=\\"error\\"&gt;Error has occured while updating the database. Please try again.&lt;/p&gt;");
echo "&lt;p&gt;Database has been updated successfully.&lt;/p&gt;";

In the database, it’s already “23” and not “2345”.

Thanks in advance,
Algirdas

OK, what you are doing is checking for an error and replacing the , or . but then using the original $_POST data in the query - so it’s never replaced in the query!

It is better to check that the str_replace function is used on the individual $_POST entity and then register them as variables.

So:


$revenues = str_replace($bad_symbols, "", $_POST['revenues']);
//etc

//and then use the variables in the query
$query = "UPDATE `financials` SET revenues='".mysql_real_escape_string($revenues)."',
// etc



Hope you understand that,

Spike

Does str_replace take an array as an argument?

Have you thought to look in the manual?
str_replace

So how does foreach() exactly work? I thought the “as” statement works analogously to passing by reference, I mean if I say foreach($smth as $smth2), then whatever I do to $smth2, the same is done to $smth, no? If so, then $_POST in my case should be amended properly. If not, then why doesn’t the step strval(intval($value)) work, i.e. doesn’t give an error since 23,45 is not a proper integer?

Finally, how come the number is cut down to an integer - which part of the code does that (it is actually cut, because if the initial value is 23 and I enter 12,34, the new value becomes 12)?

Thanks a lot! I feel like I’m learning a lot here…
Cheers,
Algirdas

foreach actually creates a copy of your array, although you can optionally use references with it starting in php5.

http://www.php.net/foreach

although you could modify the $_POST array if you wanted to, i wouldnt recomend it. generally, its a good practice to leave the superglobals like $_POST etc… alone and just read from them. if you need to change the values, create a new variable to store the changed value like spike showed you.

foreach loops through a copy of an array and the values are copied to the variables too. So any changes you make for these values do not reflect in the original array.

intval() will not give you an error, it will return the integer value. It parses the first numeric characters, so everything after “,” is omitted.

The number is cut down to an integer in the database. You probably have an integer type, so it’s the same as intval(), the integer value is parsed.

It’s the other way around. The copy is worked on by the foreach loop but changes are applied to the source array. That means if you make changes to $array[2] while working on $array[1] those changes will not be apparent from the foreach loop once $array[2] is reached.

Ok, now I’m trying it differently:


$new_data = $_POST;
$bad_symbols = array(",", ".");
for ($i = 0; $i <= count($new_data); $i++)
{
   $new_data[$i] = str_replace($bad_symbols, "", $new_data[$i]);
   if (!empty($new_data[$i]) && $new_data[$i] !== strval(intval($new_data[$i])))
	$error[$i++] = $new_data[$i];
}

When I run the file, it offers me to download an empty file with the same title as the one I’m running. If I comment the str_replace line, everything works as earlier, i.e. everything after the comma gets removed. Could anyone pls explain what’s going on?

Thanks a lot!
Algirdas

It looks like, that this new script would never pass through $_POST[‘revenues’] :wink:

Hm, weird things are happening here. This code works fine (doesn’t remove commas of course):


if (!empty($_POST))												{
   $new_data = $_POST;
   //$bad_symbols = array(",", ".");
   for ($i = 0; $i <= count($new_data); $i++)
   {
      //$new_data[$i] = str_replace($bad_symbols, "", $new_data[$i]);
      if (!empty($new_data[$i]) && $new_data[$i] !== strval(intval($new_data[$i])))
      $error[$i++] = $new_data[$i];
   }

If I uncomment the two lines, I am either offered to download an empty .php file with the same filename as the file with this code (???) or I am told that this page can’t be found (although when I access other parts of the same page, it’s shown perfectly).

What’s going on?? Why are these two seemingly simple lines creating so many problems?

Thanks,
Algirdas

turn on error reporting. it will help you find your problems.


ini_set('display_errors', 1);
error_reporting(E_ALL);

you have an endless loop is your problem. you keep recounting the $new_data array, which you keep making bigger each time you loop. it will never end.

in addition, your _POST array likely has string keys, not numeric, so you wouldnt want to use a for() loop.
a foreach loop would be easier.

foreach ($array as $key => $value) {…)

It works!! Thanks a LOT guys! What a great feeling it is when the code works as expected… (:

glad you got it sorted algirdas :smiley: