0

This condition was found in this function:

$kValues = getValueCluster($clusters, $data);
        foreach($cPos as $k => $position)
        {
                $cPos[$k] = empty($kValues[$k]) ? 0 : avg($kValues[$k]);
        }
        return $cPos

I have been trying to find out what this is. I've searched it in google and it has nothing on it.

student
  • 39
  • 4
  • http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary – j08691 Dec 12 '14 at 22:02
  • Please don't ask so fast a question! Just put 5min of effort in it! – Rizier123 Dec 12 '14 at 22:03
  • I've been searching in google and I could not find any information on it. Up until this question I found out it was an ternary operator. – student Dec 12 '14 at 22:07
  • I still don't understand when to use it and how to use it. – student Dec 12 '14 at 22:08
  • It can be used to do an `if-then-else` within an expression. **Why should I use it?** Because it is an expression. `if-then-else` is a control structure. This can be very useful when calling methods. With `if-then-else` you need to ensure, that `setSomeState()` is called in either block. – UniversE Dec 12 '14 at 22:11
  • *"I still don't understand when to use it and how to use it."* - have you bothered to read the PHP docs? It's all there buddy. – Madbreaks Dec 12 '14 at 22:31
  • I'm a slow learner but i got it down now, thanks – student Dec 13 '14 at 02:59

2 Answers2

0

That's PHP's ternary operator.

Basic example:

$x = true;
$y = $x ? 'true!' : 'false';
Madbreaks
  • 19,094
  • 7
  • 58
  • 72
0

... ? ... : ... is a ternary operator. It exists in a lot of languages. It's used like that:

variable = test ? assignIfTrue : assignIfFalse;

In your case, $cPos[$k] will be assigned to 0 if $kValues[$k] is empty and to avg($kValues[$k]) if not.

xlecoustillier
  • 16,183
  • 14
  • 60
  • 85
  • 1
    You should - for the clarity's sake - don't call it **the** ternary operator. Beginners could easily missunderstand that and start to believe, that there is only just one ternary operator in the world ;-) Better say: it *is a* ternary operator, that evaluates to the second operand, iff the first evaluates to true and to the third, otherwise. – UniversE Dec 12 '14 at 22:15
  • You're right, even if no other one comes to my mind right now. Corrected. – xlecoustillier Dec 12 '14 at 22:16