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
 [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

Pull Requests

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-2024 The PHP Group
All rights reserved.
Last updated: Sun Dec 22 05:01:30 2024 UTC