To add to a variable in a foreach loop in PHP, you can use the addition assignment operator (+=). Here's an example:

$numbers = array(1, 2, 3, 4, 5);
$total = 0;

foreach ($numbers as $number) {
    $total += $number;
}

echo 'The total is: ' . $total; // Output: The total is: 15

In this example, we have an array of numbers and a variable $total initialized to 0. Inside the foreach loop, we use the addition assignment operator to add each number to $total. Finally, we print out the total.

PHP Foreach Loop: Adding to a Variable

原文地址: https://www.cveoy.top/t/topic/m8ze 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录