0

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

1 Answer 1

1

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]);
Sign up to request clarification or add additional context in comments.

2 Comments

Wow, thanks! I'll accept your answer when the wait is up :)
No problem. As a side note, if you have to run the code frequantly (eg not just a weekly report of something) then i would refactor the database to include the required data in integar columns, so you can do the math in SQL its self

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.