简体   繁体   中英

Ternary expression containing loose comparison in else branch yields unexpected result

Could someone help me with this code? On my website, there is no result.

<?php
if (isset($_GET['id']) ? $product['valid2'] : ''==1) {
    echo "Yes";
} elseif (isset($_GET['id']) ? $product['valid2'] : ''==0) {
    echo "No";
}

From your comments it seems like you just want to check that the id is set or that it isn't assigned to 0.

This can be achieved using a simple check that it exists and then casting the value to Boolean. This will assign the value of > 0 to true and 0 to false.

$id = filter_input(INPUT_GET, 'id');
$idIsSet = (bool) $id;

if (!$idIsSet) {
    // Id is not set so do something to handle this.
    echo "No";
    die();
}

// The Id is set so you can do whatever you want with the Id.
echo "Yes";

I solved it with this function:

<?php
          
$v2 = isset($_GET['id']) ? $product['valid2'] : '';          
 
          
if ($v2==1) {
    echo "Yes";
} elseif ($v2==0) {
    echo "No";
}

?> 

Thanks for all answers!

According toOperator Precedence rules in php (which can change between different php versions), the loose "comparison" ( == ) enjoys a higher precedence than the "ternary" ( ? : ).

This means that the loose comparison portion is evaluated before the isset() check.

It is also important to express that from php8 ''==0 evaluates as false , while in versions under php8 the same expression evaluates as true . Resource: https://www.php.net/manual/en/migration80.incompatible.php

Boiled down, your if and elseif expressions are doing truthy/falsey checks.

  1. As stated earlier, the loose comparison branch of the ternary expression is performed first.
  2. If isset($_GET['id']) is true, the the value of $product['valid2'] is evaluated as truthy/falsey.
  3. If isset($_GET['id']) is false, the the value of the loose comparison is evaluated as truthy/falsey.

Without knowing your project intimately, it may be direct, correct, and readable to express the logic in the following manner.

echo isset($_GET['id']) && $product['valid2'] == 1 ? 'Yes' : 'No';

This is not meant to duplicate your code's logic, but to improve it and ensure that you always receive a yes/no outcome.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM