-4

I'm trying to convert this PHP function to Objective-C. I can just barely read PHP to figure out what the code does. Came across this line and stopped:

$nr = (strlen($nr)-3>0)?substr($nr, 0, strlen($nr)-3):"";

What do the ? and : do here? I read the documentation to see what strlen and substr do but haven't been able to figure out how this comes together and what the new value of $nr is.

Bakuriu
  • 98,325
  • 22
  • 197
  • 231
unom
  • 11,438
  • 4
  • 34
  • 54
  • The code is not Python, but `?:` is the ternary operator: http://en.wikipedia.org/wiki/%3F: – NPE Sep 07 '14 at 20:41
  • I think everyone's missing the point, focusing on the Python vs PHP rather than the actual question about the ternary operator. – FeifanZ Sep 07 '14 at 20:44
  • Ok. It's PHP, sorry about that. – unom Sep 07 '14 at 20:44
  • 1
    @FeifanZ The actual question is a clear duplicate. Next time, instead of hunting reputation answering it with a cheap answer, search for the duplicate and vote to close. – Bakuriu Sep 07 '14 at 20:47
  • Sorry about this. It was my mistake, as I got PHP confused with Python. I accepted an answer and gave the runners up votes. Thank you so much for the quick answer! – unom Sep 07 '14 at 20:55

3 Answers3

2

The ?: is a ternary operator. The expression x ? y : z means if x then y else z. In this case, it would translate to something like

if strlen($nr) - 3 > 0:
    $nr = substr($nr, 0, strlen($nr) - 3)
else:
    $nr = ''
FeifanZ
  • 16,250
  • 7
  • 45
  • 84
  • It's a ternary operator in some languages, but in python it's just invalid syntax. – Bill Lynch Sep 07 '14 at 20:41
  • True... sorry about this... it's PHP. I'm about as good at PHP as I am at Python. Edited the title and tag. – unom Sep 07 '14 at 20:46
  • Your answer seems to be the correct one. Something along the lines of: $var = (condition) ? if_true : if_false – unom Sep 07 '14 at 20:51
  • ?: is the ternary operator. If condition is true, $var will be assigned the value if_true; otherwise it will be assigned the value if_false. I found this on another thread... so another 2 min and I will be able to accept the answer. Thank you! – unom Sep 07 '14 at 20:52
2

This is not Python, but if you were to break it into psuedo-Python syntax it would be

if strlen($nr) - 3 > 0:
     $nr = substr($nr, 0, strlen($nr)-3)
else:
     $nr = ""

In various languages, the ? operator is a ternary operator. This syntax does not exist in Python. The above is how you would write such a statement, though you'd have to correct the syntax in each of the if blocks, as well as the if condition.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

it will translate to

if (strlen($nr)-3>0) then value of $nr is substr($nr, 0, strlen($nr)-3) 
else it is "" 

And i dont think the code is in python it looks like php or perl.

subas_poudel
  • 456
  • 2
  • 17