Hi,

I got this long version code:

    if(ISSET($_GET['limit']))
    {
        $limit = intval($_GET['limit']);
    }
    else
    {
        $limit = intval(1);
    }

I can shorten it, like this and it works:

$limit = ISSET($_GET['limit'])?intval($_GET['limit']):1;

Now add an echo and try shortening it. And I get error.

I got this long code with echo in it:

    if(ISSET($_GET['limit']))
    {
        $limit = intval($_GET['limit']);
        echo "<option value=\"$limit\">$limit</option>";
    }
    else
    {
        $limit = intval(1);
    }

Now, how do I shorten it ?
These 2 fail! Show error:

1

$limit = ISSET($_GET['limit'])?intval($_GET['limit']);echo "<option value=\"$limit\">$limit</option>";:1;

2

$limit = (ISSET($_GET['limit'])?intval($_GET['limit']);echo "<option value=\"$limit\">$limit</option>";:1)

Dani AI

Generated

is spot on: the ternary is an expression that yields a value, not a place to sprinkle statements. Your failing examples break the cond ? expr1 : expr2 shape with semicolons, and try to use echo inside the operands. You can either build a string with the ternary and echo that, or keep output separate from assignment.

A concise, readable pattern:

$limit = (int) ($_GET['limit'] ?? 1);     // PHP 7+: null coalescing, defaults to 1
if (isset($_GET['limit'])) {
    printf('<option value="%d">%d</option>', $limit, $limit);
}

If you really want a one-liner for the output, keep echo outside the ternary and let the ternary produce the string:

$limit = (int) ($_GET['limit'] ?? 1);
echo isset($_GET['limit']) ? "<option value=\"$limit\">$limit</option>" : "";

Bonus: validate the input in one step and still keep the default. This avoids negatives or non-numeric values:

$limit = filter_input(
    INPUT_GET,
    'limit',
    FILTER_VALIDATE_INT,
    ['options' => ['default' => 1, 'min_range' => 1]]
);
if (filter_has_var(INPUT_GET, 'limit')) {
    printf('<option value="%d">%d</option>', $limit, $limit);
}

Small notes:

  • echo cond ? ... : ... is fine, but cond ? echo ... : ... is not.
  • Casting to (int) (or using filter_input) makes the output safe for HTML in this case. If you ever switch to non-numeric output, escape with htmlspecialchars().

Recommended Answers

All 2 Replies

@rproffitt

How to fix the bug without your whip here ? Lol!

The shorthand of using ? and : is for assigning a value to a single variable in a simple and concise way.

Not everything is meant to be written in shorthand. When you have multiple things you want to do, echo something in a if-block but not in the else block, etc., then that’s what code blocks are for.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.