PHP中加法返回字符串拼接结果,求实现10+12=22的解决方案
Hey there! Let's break down why your addition is turning into string concatenation and fix that weird 01012 result instead of the expected 22.
Common Causes & Solutions
1. You're Using the Wrong Operator
First things first—double-check the operator in your code. PHP uses . for string concatenation and + for numeric addition. It’s super easy to mix these up by mistake!
// ❌ Wrong: This concatenates strings, giving "1012" or "01012" $result = $value1 . $value2; // ✅ Correct: This adds the numeric values, giving 22 $result = $value1 + $value2;
2. Values Are Stored/Retrieved as Strings
If your database fields are set to string types (like VARCHAR or CHAR), even if they look like numbers, PHP will treat them as strings. Automatic type conversion might fail sometimes—especially if there are leading zeros (like "010" instead of 10).
Force conversion to integers to ensure proper addition:
// Option 1: Cast to integer directly $num1 = (int) $dbValue1; $num2 = (int) $dbValue2; $result = $num1 + $num2; // Option 2: Use intval() for explicit control // Add 10 as the second parameter to force decimal conversion (avoids octal issues in older PHP versions) $num1 = intval($dbValue1, 10); $num2 = intval($dbValue2, 10); $result = $num1 + $num2;
3. Database Field Type Mismatch
If you’re storing numeric values, use numeric field types (like INT, BIGINT, or DECIMAL) instead of string types. This way, when you fetch values from the database, they’ll already be numeric in PHP, so addition works as expected without extra conversion steps.
4. Debug to Confirm Types
If you’re still stuck, use var_dump() to check the type and value of your variables. This will help you confirm if they’re strings or numbers:
var_dump($dbValue1, $dbValue2); // Example output if they're strings: string(2) "10" string(2) "12" // Example output if they're integers: int(10) int(12)
Quick Recap
- Use
+for addition, not. - Convert string values to integers before adding
- Use numeric database fields for numeric data
- Debug with
var_dump()to verify variable types
内容的提问来源于stack exchange,提问作者Sinju Mathew

