-
AuthorPosts
-
March 22, 2017 at 12:56 pm #764743
Hello
I’m a bit new to PHP so could be very wrong here, but I was going through the loop-index.php file so that I could add the_author() to the grid layout and found this line which I just couldn’t understand:
$size = strpos($blog_style, ‘big’) ? (strpos($current_post[‘post_layout’], ‘sidebar’) !== false) ? ‘entry_with_sidebar’ : ‘entry_without_sidebar’ : ‘square’;
I researched a little bit about ternary operators for if/else alternatives but could not find any resource for such syntax where there are multiple ‘:’ without a ‘?’ in between and the parentheses are not wrapped according to ternary operator stacking conventions.
This is just to cure my curiosity as a beginner. Please let me know what this means. Thanks a ton!
March 23, 2017 at 12:33 pm #765373Hey architchandra,
Thanks for contacting us :) You can see lots of : with ? before because it’s an alternative syntax for control structures for example instead of:
if( condition ) { statement; } else { statement; }
You’ll find:
if( condition ) : statement; else: statement; endif;
Or instead of:
while (have_posts()) { statement; }
You’ll have:
<pre><code>while (have_posts()) : statement; endwhile;
There are a lot more but you can research on that. Hope you find this helpful :)
Best regards,
NikkoMarch 23, 2017 at 2:00 pm #765442Hello Nikko
Thank you for trying, but you’ve not been able to answer my question properly.
I understand that
if(condition) {
statement 1;
} else {
statement 2;
}can be written as
if(condition):
statement 1;
else:
statement 2;
endif;or as
$variable = condition ? statement 1 : statement 2;
I understand these, but if you notice the code statement that I mentioned, it doesn’t seem to fall under any of these categories, although it seems like it should fall in category 3. Notice that a ? statement follows another ? statement directly (might have made sense if the parentheses were put in differently). Also notice that there is : statement right after another : satement. That to me is not making sense.
Please help me understand this. Thanks.
March 23, 2017 at 2:21 pm #765469Hi,
Okay, it’s simple it’s a nested ternary operator.
$size = strpos($blog_style, ‘big’) ? (strpos($current_post[‘post_layout’], ‘sidebar’) !== false) ? ‘entry_with_sidebar’ : ‘entry_without_sidebar’ : ‘square’;I make the inner one bold. So it’s like if
strpos($blog_style, 'big')
is true (or has value) then it performs another ternary operation
(strpos($current_post['post_layout'], 'sidebar') !== false) ? 'entry_with_sidebar' : 'entry_without_sidebar'
I hope my explanation is good :)
Best regards,
Nikko- This reply was modified 7 years, 9 months ago by Nikko.
March 23, 2017 at 2:29 pm #765479Thanks Nikko. I will try this out and let you know whether it worked or not. :)
March 23, 2017 at 2:32 pm #765483Hi,
You’re welcome. Just comment back on this thread if you need help :)
Best regards,
Nikko -
AuthorPosts
- You must be logged in to reply to this topic.