# 1. Classic
# 2. Weird
# 3. With Breaks
# 4. Short
# 5. Even Shorter
1.) Classic
===========
<?php
if($foo) {
// $foo
} else {
// empty
}
?>
2.) Weird
=========
<?php
if($foo):
// $foo
else:
// empty
endif;
?>
3.) With Breaks
===============
<?php if($foo): ?>
<!-- $foo -->
<? else: ?>
<!-- empty -->
<? endif; ?>
4.) Short
=========
<?php
echo $foo ? $foo : 'fallback';
// is $foo empty
echo !empty($foo) ? $foo : 'empty'; // $foo or 'empty'
// is 5 greater than 1?
echo 5 > 1 ? 'yes' : 'no'; // 'no'
// Does 'a' equal 'b'?
echo 'a' == 'b' ? 'equals' : 'no'; // 'no'
?>
5.) Even Shorter
===================================
"The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand."
– from: https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op)
<?php
echo $foo ?: 'fallback'; // $foo or 'fallback', also called "Elvis operator", equals `$foo ? $foo : 'fallback'`
echo !empty($foo) ?: 'fallback'; // $foo or 'fallback', also called "Elvis operator", equals `!empty($foo) ? $foo : 'fallback'`
echo $foo ?? 'fallback'; // $foo or 'fallback', equals `isset($foo) ? $foo : 'fallback'`
?>
6.) Other Fancy Stuff aka Spaceship operator
============================================
"The spaceship operator is used for comparing two expressions. It returns -1, 0 or 1 when $a is respectively less than, equal to, or greater than $b. Comparisons are performed according to PHP's usual type comparison rules."
– https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.spaceship-op
<?php
// Integers
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1
// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1
// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1
?>
5 kurze If / Else (Wenn / Dann) Schreibweise in PHP (inkl. Elvis operator)
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.