PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label conditional-operator. Show all posts
Showing posts with label conditional-operator. Show all posts

Tuesday, December 20, 2022

[FIXED] What is the Java ?: operator called and what does it do?

 December 20, 2022     conditional-operator, java, syntax, ternary-operator     No comments   

Issue

I have been working with Java a couple of years, but up until recently I haven't run across this construct:

int count = isHere ? getHereCount(index) : getAwayCount(index);

This is probably a very simple question, but can someone explain it? How do I read it? I am pretty sure I know how it works.

  • if isHere is true, getHereCount() is called,
  • if isHere is false getAwayCount() is called.

Correct? What is this construct called?


Solution

Yes, it is a shorthand form of

int count;
if (isHere)
    count = getHereCount(index);
else
    count = getAwayCount(index);

It's called the conditional operator. Many people (erroneously) call it the ternary operator, because it's the only ternary (three-argument) operator in Java, C, C++, and probably many other languages. But theoretically there could be another ternary operator, whereas there can only be one conditional operator.

The official name is given in the Java Language Specification:

§15.25 Conditional Operator ? :

The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.

Note that both branches must lead to methods with return values:

It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.

In fact, by the grammar of expression statements (§14.8), it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear.

So, if doSomething() and doSomethingElse() are void methods, you cannot compress this:

if (someBool)
    doSomething();
else
    doSomethingElse();

into this:

someBool ? doSomething() : doSomethingElse();

Simple words:

booleanCondition ? executeThisPartIfBooleanConditionIsTrue : executeThisPartIfBooleanConditionIsFalse 


Answered By - Michael Myers
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, June 26, 2022

[FIXED] how this Ternary Operator work with this statemnt?

 June 26, 2022     boolean-expression, compiler-errors, conditional-operator, java     No comments   

Issue

i just generate this methode to find max val in some matrix and somehowe i was able to change int val insdie Ternary Operator (java 8)

int  max=0, indexToReturn=0;
        int size= arr[0].length;
        for (int i=1 ; i < size ; i++)
        {
            //
            //                                                 ¯\_(ツ)_/¯
            max =  (!(arr[j][indexToReturn] > arr[j][i])) ? indexToReturn= i : arr[j][indexToReturn] ;
        }
     return max > 0 ||  indexToReturn==size-1 ? arr[j][indexToReturn] : null;

(the method compile and working)

im not realy sure evan how its compile from what i saw online Ternary Operator syntax :

variable = Expression1 ? Expression2: Expression3

can someone explain me what im missing here ?


Solution

The reason this works is because an assignment is an expression. The value of an assignment is the value assigned. This sounds theoretical, so let us look at an example:

int i, k;
i = (k = 5);
System.out.println(i);
System.out.println(k);

Ideone demo

The value of the expression k = 5 is the assigned value 5. This value is then assigned to i.

Armed with this knowledge, we see that indexToReturn= i is an expression that evaluates to the value of i. When we swap Expression2 and Expression3, the ternary operator breaks because the = i is not evaluated as part of the ternary operator (due to operator precedence). If we set parentheses around Expression2, it works as expected.


I would discourage using the fact that an assignment is an expression. (Ab)using this fact often leads to hard-to-understand code.



Answered By - Turing85
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, December 31, 2021

[FIXED] Using ternary operator inside select option tag

 December 31, 2021     codeigniter, conditional-operator, html, php     No comments   

Issue

Currently I have a select box that is filling in its data from the controller class. As of now all the values are filling in properly as intended, but there are some null values for firstname for which I'm trying to add a ternary operator to replace it with email.

This doesn't seem to work in my controller class as I'm placing the parentheses wrong.

Here's my current code:

public function getContacts($id){
    $option = "<option value='0'>Select</option>";

    $modelList = $this->listings_model->get_contact(array('contact_type'=>3),'firstname,lastname,email,refno');  
    foreach($modelList as $m){
        $option .= "<option value='".$m['firstname']." ".$m['lastname']." - ".$m['refno']."' id='".$m['id']."'>".$m['firstname']." ".$m['lastname']." - ".$m['refno']."</option>";
    }

    echo json_encode($option);
} 

I've tried the following but I'm getting a syntax error:

$option .= "<option value='"($m['firstname'].$m['lastname'] ? $m['firstname']." ".$m['lastname']." - ".$m['refno'] : $m['email'])"' id='".$m['id']."'>".$m['firstname']." ".$m['lastname']." - ".$m['refno']."</option>";

What I want to achieve is this:

value="<?php echo ($ow['firstname'].$ow['lastname']?$ow['firstname'].' '.$ow['lastname']:($ow['email']?$ow['email']:$ow['mobile'])).' - '.$ow['refno']; ?>"


Solution

We have these things called variable that help code become readable. Also, parentheses can help identify groups of variables with operations between them in a ternary operator. You have several misplaced ' and " in your code, both in PHP and in HTML.

From what I understand from your requirements the following code does this: if firstname and lastname are not empty it will use <firstname> <lastname> - <ref> for the value and text of the option else it will use <email> if email is not empty else <mobile>

$name = ( $m['firstname'] && $m['lastname'] ) ? ( $m['firstname'] . ' ' . $m['lastname'] ) : ( '' );
$value = $name ? ($name . ' - ' . $m['refno']) : ($m['email'] ? $m['email'] : $m['mobile']);
$id = $m['id'];
$option .= "<option value=\"$value\" id=\"$id\">$value</option>";

By the way, you cannot json_encode an HTML string.



Answered By - A. Rahimi
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing