What is ":" in PHP?

符号是什么意思:在PHP中是什么意思?


PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.


You also encounter : if you use the alternative syntax for control structures:

<?php
if ($a == 5):
    echo "a equals 5";
    echo "...";
elseif ($a == 6):
    echo "a equals 6";
    echo "!!!";
else:
    echo "a is neither 5 nor 6";
endif;
?>

Or as already mentioned the ternary operator:

$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

(Examples taken from the documentation)


Edit: Somehow I didn't see that the alternative syntax was already mentioned, must be too tired ;) Anyway, I will leave it as it is, as I think an actual example and a link to the documentation is more helpful than just plain text.


I'm guessing you're seeing this syntax:

print ($item ? $item : '');

This is a short form of if/else. The ? is the if, and the : is the else.

链接地址: http://www.djcxy.com/p/1742.html

上一篇: “:”在PHP中意味着什么?

下一篇: 什么是PHP中的“:”?