You are viewing a single thread.
View all comments View context
11 points

Halp. I don’t understand how it went from step 2 to step 3.

permalink
report
parent
reply
32 points

It’s cause PHP associates the if-then-else pair only with its immediate “else” option, not with the entirety of the line.

Let’s go by parts.

$a == 1 ? "one" : $a == 2 ? "two" : $a == 3 ? "three" : "other"

Is $a equal to 1? If so, we’re “set” to the value on the left, which is "one", if not then we’re set to the value on the right, which is $a == 2. $a is not equal to 1, so we’re set to the right value, $a == 2.

This replaces the relevant part, $a == 1 ? "one" : $a == 2, with $a == 2. So we’re left with:

$a == 2 ? "two" : $a == 3 ? "three" : "other"

Next, is $a equal to 2? If so, we’re set to "two", if not we’re set to $a == 3. The comparison is true, so we’re set to the value on the left, "two". The relevant part here is $a == 2 ? "two" : $a == 3 only, so it replaces it with "two" cause again, PHP is only associating with its immediate pair. So now we’re left with:

"two" ? "three" : "other"

Finally, is "two" truthy? If so, we’re set to "three", if not we’re set to "other". Since "two" is truthy we’re then left with "three".

It’s super confusing for sure.

permalink
report
parent
reply
5 points

Thanks! I never worked with PHP but I understand your explanation. Making memes about languages is also about learning

permalink
report
parent
reply
3 points

Thank you!

permalink
report
parent
reply
5 points

Thank you for the great explanation, and for teaching me the word “truthy.”

permalink
report
parent
reply

Programmer Humor

!programmerhumor@lemmy.ml

Create post

Post funny things about programming here! (Or just rant about your favourite programming language.)

Rules:

  • Posts must be relevant to programming, programmers, or computer science.
  • No NSFW content.
  • Jokes must be in good taste. No hate speech, bigotry, etc.

Community stats

  • 3.7K

    Monthly active users

  • 1.5K

    Posts

  • 35K

    Comments