Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Sum (+)

The `+` operator adds two numbers, such as the order subtotal and the delivery charge.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

$value + $operand

The + operator adds two numbers, such as the order subtotal and the delivery charge. In PHP 8 a numeric string converts to a number. A leading number followed by text triggers a warning, and a string without a numeric prefix raises TypeError. Two array operands form a union by key. At a shared key the left array supplies the value.

With integer operands a result within the integer range stays an integer. Overflow can produce a float and lose precision.

Evaluation

  • 16 + 5 → 21
  • (-4) + 4 → 0
  • 3 + 0 → 3
  • "12.5" + 2 → 14.5
  • ['a'=>3] + ['a'=>9,'b'=>4] → {"a":3,"b":4}
  • 'free' + 2 → TypeError

Examples

<?php
echo json_encode(16 + 5), PHP_EOL;

echo json_encode((-4) + 4), PHP_EOL;

echo json_encode(3 + 0), PHP_EOL;

echo json_encode("12.5" + 2), PHP_EOL;

echo json_encode(['a'=>3] + ['a'=>9,'b'=>4]), PHP_EOL;

try {
    echo 'free' + 2;
} catch (TypeError $error) {
    echo get_class($error), PHP_EOL;
}

Result

21
0
3
14.5
{"a":3,"b":4}
TypeError

Sources