The Codesee
The Codesee

Reputation: 3781

Using a loop to simplify preg_replace

Am I able to simplify this code? I am getting five strings from a SELECT query, stripping them down to only numbers and adding them.

$sum = preg_replace("/[^0-9]/","",$row['AB']) + preg_replace("/[^0-9]/","",$row['CD']) + preg_replace("/[^0-9]/","",$row['EF']) + preg_replace("/[^0-9]/","",$row['GH']) + preg_replace("/[^0-9]/","",$row['IJ']);

Can I do something like this:

preg_replace("/[^0-9]/","",$sum = $row['AB'] + $row['CD'] + $row['EF'] + $row['GH'] + $row['IJ']);

Upvotes: 0

Views: 52

Answers (1)

Steve
Steve

Reputation: 20469

You can write a simple loop to reduce code duplication:

Provided your sql only selects the required columns:

$sum = 0;
foreach($row as $item)
    $sum += preg_replace("/[^0-9]/","",$item);

If you have more columns in the row (and you actually need that data so you cant just alter the SQL):

$sum = 0;
foreach(['AB','CD','EF','GH','IJ'] as $key)
    $sum += preg_replace("/[^0-9]/","",$row[$key]);

Upvotes: 1

Related Questions