php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #45716 Addition and minus operators do not work properly when appended to a string
Submitted: 2008-08-05 07:39 UTC Modified: 2008-08-05 07:57 UTC
From: pasamio at gmail dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.2.6 OS: Linux 2.6.5-7.191-smp
Private report: No CVE-ID: None
 [2008-08-05 07:39 UTC] pasamio at gmail dot com
Description:
------------
When using a simple addition or minus operator that is prepended by a string and concatenated to it will fail to work properly if the string has a value. When the string is empty (e.g. '' or ' ') it will work properly. The multiplication and division functions operate appropriately.

Reproduce code:
---------------
<?php
$x = 10;
$i = 2;

echo "Addition Test\n";
echo 'Test 1: '. $x + $i . "\n";
echo 'Test 2: '. ($x + $i) .  "\n";
echo 'Test 3: ';
echo $x + $i . "\n";
echo 'Test 4: ';
echo ''. $x + $i ."\n";
echo "\n";

echo "Subtraction Test\n";
echo 'Test 1: '. $x - $i . "\n";
echo 'Test 2: '. ($x - $i) .  "\n";
echo 'Test 3: ';
echo $x - $i . "\n";
echo 'Test 4: ';
echo 'x'. $x - $i ."\n";
echo "\n";


Expected result:
----------------
moffats@dev1:~/public_html/testing> php bug-minus.php
Addition Test
Test 1: 12
Test 2: 12
Test 3: 12
Test 4: 12

Subtraction Test
Test 1: 8
Test 2: 8
Test 3: 8
Test 4: 8



Actual result:
--------------
moffats@dev1:~/public_html/testing> php bug-minus.php
Addition Test
2
Test 2: 12
Test 3: 12
Test 4: 12

Subtraction Test
-2
Test 2: 8
Test 3: 8
Test 4: 8



Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2008-08-05 07:42 UTC] derick@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

This is because of operator precedence, see: http://no2.php.net/manual/en/language.operators.php
 [2008-08-05 07:57 UTC] pasamio at gmail dot com
Apologies, didn't think that it would have the same precendence given that the two operators do two completely different type conversions (one to numeric and the other to a string). I guess thats something copied from Perl which appears to use a similar methodology.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Mon Jul 21 11:00:02 2025 UTC