php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #70618 Ternary eccentricity
Submitted: 2015-10-01 21:42 UTC Modified: 2015-10-02 00:32 UTC
From: symphonymous at hotmail dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.6.14RC1 OS: Ubuntu
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: symphonymous at hotmail dot com
New email:
PHP Version: OS:

 

 [2015-10-01 21:42 UTC] symphonymous at hotmail dot com
Description:
------------
I suspect this is a bug as the behaviour is a little worrying.

I was using the following in a Laravel program

    $fieldLabel = // has a field label been manually defined
      ($fieldLabel =  $this->hasAttribute($fieldValue, 'FieldLabel'))
      ? $fieldLabel
      : ($this->parseFieldType($fieldValue) != 'hidden')         
        ? ucfirst($fieldKey)
        : '';

However when $label was defined it was resolving to 
$fieldLabel = ucfirst($fieldKey); 

(ie. the second ternary).

the resolution was to parenthesise the second ternary (which I should have done in the first place):

    $fieldLabel = // has a field label been manually defined
      ($fieldLabel =  $this->hasAttribute($fieldValue, 'FieldLabel'))
      ? $fieldLabel
      : (($this->parseFieldType($fieldValue) != 'hidden')         
        ? ucfirst($fieldKey)
        : '');

The bug, in my eyes, is that aforementioned code should have thrown an exception as the ternary statement gave an ambiguous result.

best

Jon

Test script:
---------------
// here is the same issue again in a simpler form, tested with 
// "php artisan tinker"

$foo = 1;

$bar = ($bar = $foo) ? $bar : ($bar = 2) ? 2 : 'null';

Expected result:
----------------
either an exception as the statement is ambiguous or 1;

I would suggest the former.

Actual result:
--------------
2

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2015-10-02 00:32 UTC] requinix@php.net
-Status: Open +Status: Not a bug -Package: PHP Language Specification +Package: Scripting Engine problem
 [2015-10-02 00:32 UTC] requinix@php.net
Eccentric yes, bug no. Backwards compatibility is the biggest hurdle, so if it were to change in the future then it would likely be made non-associative (ie. parentheses would be required). Besides, parentheses also help to make it explicit to the reader about how the logic works.

There was a discussion about this a while back: http://markmail.org/thread/5bjy2xnu2vrgxxmy
 
PHP Copyright © 2001-2026 The PHP Group
All rights reserved.
Last updated: Tue Oct 06 09:00:02 2026 UTC