php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #71467 -2 **2 = -4
Submitted: 2016-01-27 23:27 UTC Modified: 2016-02-03 19:15 UTC
From: public at grik dot net Assigned:
Status: Not a bug Package: Math related
PHP Version: 7.0.3RC1 OS: unrelated
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: public at grik dot net
New email:
PHP Version: OS:

 

 [2016-01-27 23:27 UTC] public at grik dot net
Description:
------------
In 5.6 the operator ** appeared, but its behavior is very unexpected.

echo -2 ** 2; gives -4


Test script:
---------------
echo -2 ** 2;

Expected result:
----------------
4

Actual result:
--------------
-4

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-01-27 23:38 UTC] requinix@php.net
-Status: Open +Status: Wont fix
 [2016-01-27 23:38 UTC] requinix@php.net
** has higher precedence than -
http://php.net/manual/en/language.operators.precedence.php

-2 ** 2 => -(2 ** 2)

The programming world is split on whether power/exponentiation ranks higher or lower than negation - PHP chose the higher side, which also includes Python and Perl.
 [2016-01-27 23:40 UTC] danack@php.net
-Status: Wont fix +Status: Not a bug
 [2016-01-27 23:40 UTC] danack@php.net
Hello,

According to the page http://php.net/manual/en/language.operators.precedence.php

The ** operator has higher precedence than the - operator.

The code you posted is equivalent to:

echo -(2 ** 2);

You can get the result you probably desired by doing:

echo (-2) ** 2;


Parentheses are your friends.
 [2016-02-03 19:15 UTC] cmb@php.net
-Package: PHP Language Specification +Package: Math related
 
PHP Copyright © 2001-2020 The PHP Group
All rights reserved.
Last updated: Fri Oct 30 20:01:24 2020 UTC