In response to the note concerning references below, his point is taken, albeit in the wrong context. According to the section on references (http://www.php.net/manual/en/language.references.return.php), returning by reference means you return a variable by reference, not an expression. The ternary operator is an expression, which is why his example doesn't work (it also generates an E_NOTICE, "Only variable references should be returned by reference...").
I mentioned the wrong context because the ternary operator has nothing to do with alternative syntax (e.g. if: ... endif;); it is its own alternative to the alternative. As it were.
Word.
Алтернативен синтаксис за контролни структури
PHP предоставя алтернативен синтаксис за някои от контролните структури, а именно: if, while, for, foreach и switch. Във всички случаи, основната форма на алтернативния синтаксис се получава като се смени отварящата фигурна скоба на двоеточие и затварящата къдрава скоба съответно на endif;, endwhile;, endfor;, endforeach; или endswitch;.
<?php if ($a == 5): ?>
A е равно на 5
<?php endif; ?>
В горния пример, HTML блокът "A е равно на 5" е вложен в конструкция if, написана с алтернативния синтаксис. HTML блокът ще бъде изведен само ако $a е равна на 5.
Алтернативният синтаксис важи също и за else и elseif. Следващият пример представлява структурата if с elseif и else в алтернативен формат:
<?php
if ($a == 5):
echo "a е равно на 5";
echo "...";
elseif ($a == 6):
echo "a е равно на 6";
echo "!!!";
else:
echo "a не е нито 5, нито 6";
endif;
?>
Алтернативен синтаксис за контролни структури
tmont
02-Jun-2008 12:17
02-Jun-2008 12:17
protractor at gmx dot net
28-Apr-2008 05:21
28-Apr-2008 05:21
If you use alternative syntax beware that references will be broken.
I hope this helps someone.
example:
<?php
class myclass
{
public $arr = NULL;
public function &get($name) // should return a reference
{
return isset($this->arr[$name]) ? $this->arr[$name] : NULL;
}
public function &get_by_ref($name) // returns a reference
{
if(isset($this->arr[$name]))
{
return $this->arr[$name];
}else{
return NULL;
}
}
}
$cl = new myclass();
$cl->arr['a'] = 'a';
$out =& $cl->get('a');
echo $out; // a
$cl->arr['a'] = 'b';
echo $out; // a
$cl = new myclass();
$cl->arr['a'] = 'a';
$out =& $cl->get_by_ref('a');
echo $out; // a
$cl->arr['a'] = 'b';
echo $out; // b
?>
Anonymous
21-Apr-2008 06:59
21-Apr-2008 06:59
to martin at rootshell dot cz:
It is called short-circuit evalution same as in C/C++, Javascript, etc.
It is stated here:
http://www.php.net/manual/en/language.operators.logical.php
Another use of this "feature" is like this:
<?php
// Long Version:
if(!empty($_REQUEST["name"])) $name = $_REQUEST["name"];
else $name = "Anonymous";
// Can be written as:
($name = @$_REQUEST["name"]) or ($name = "Anonymous");
?>
martin at rootshell dot cz
10-Apr-2008 01:31
10-Apr-2008 01:31
What about this ?? And it's actually works.
<?php
$filename = '/path/to/data-file';
$file = fopen ($filename, 'r')
or die("Can't open the file ($filename)");
?>
jeremia at gmx dot at
28-Jan-2008 03:52
28-Jan-2008 03:52
If you wan't to use the alternative syntax for switch statements this won't work:
<div>
<?php switch($variable): ?>
<?php case 1: ?>
<div>
Newspage
</div>
<?php break;?>
<?php case 2: ?>
</div>
Forum
<div>
<?php break;?>
<?php endswitch;?>
</div>
Instead you have to workaround like this:
<div>
<?php switch($variable):
case 1: ?>
<div>
Newspage
</div>
<?php break;?>
<?php case 2: ?>
</div>
Forum
<div>
<?php break;?>
<?php endswitch;?>
</div>
php dot net at eoasys dot com
25-Oct-2007 12:03
25-Oct-2007 12:03
In response to spa:
Yeah, that's for sure! Seems so obvious, but remains a tough sell... I avoid the "Bracket Racket", and use it only where the (ahem) "Clearer Syntax" wasn't implemented.
A further improvement would be a "Noun-Verb" form of end structures. Such as:
if (...):
while (...):
...
if (...):
...
...
ifend;
...
whileend;
ifend;
This would make it yet another level of easier to tell which block end you're looking at. ;-)
spa
17-Oct-2007 01:40
17-Oct-2007 01:40
In response to virtuall:
The end_; structure sometimes makes it easier to tell which block statement end you are looking at. It's much harder to tell which nested block a } belongs to than an end_;
php dot net at eoasys dot com
19-Sep-2007 01:57
19-Sep-2007 01:57
Amen to what "atw" said.
It's really amazing how off-topic many notes on this page are. It is specifically about ENDcontrol structures. Of the twelve notes below, only one even mentions the word END. Perhaps only three or four are directly on-topic!
oly at czo dot net
27-Jun-2007 10:59
27-Jun-2007 10:59
3 Lines to make table row colors alternate. Could be used for other applications as well.
<?
//1. Initialize alternating variable.
$alt_color=true;
while($row=mysql_fetch_array($result)){
//2. If alt var true set one color if false set the other.
echo (($alt_color) ? "<tr bgcolor=\"#ffffff\">\n" : "<tr bgcolor=\"#D9E5F1\">\n");
echo "<td>echo $row['id'];;</td>\n";
echo "</tr>\n";
//3. Alternate the variable value;
(($alt_color) ? $alt_color=false : $alt_color=true);
}
?>
geekman at Textbook Torrents dot com
01-Apr-2007 12:09
01-Apr-2007 12:09
The bug in your example is user error.
<?
$foobar = 2;
echo 'Foobar is ' . ($foobar == 2) ? 'foo' : 'bar';
// outputs 'foo';
echo 'Foobar is ' . (($foobar == 2) ? 'foo' : 'bar');
// outputs 'Foobar is foo';
?>
When using the ? : operators you should always wrap the entire thing in parentheses to avoid the problem you describe. By my understanding, the issue an extension of your example:
<?
$pet-type = 1;
$pet-name = 'Mittens';
echo 'My ' . ($pet-type == 1) ? 'cat' : 'puppy' . 'dog' . '\'s name is ' . $pet-name . '.';
// returns 'cat'
echo 'My ' . (($pet-type == 1) ? 'cat' : 'puppy' . 'dog') . '\'s name is ' . $pet-name . '.';
// returns 'My cat\'s name is Mittens.'
?>
You see that without parentheses the parser has no way of differentiating between the false case and the rest of the string.
fernandoleal at dragoncs dot com
03-Feb-2007 08:17
03-Feb-2007 08:17
If you need nested ifs on I var its important to group the if so it works.
Example:
<?php
//Dont Works
//Parse error: parse error, unexpected ':'
$var='<option value="1" '.$status == "1" ? 'selected="selected"' :''.'>Value 1</option>';
//Works:
$var='<option value="1" '.($status == "1" ? 'selected="selected"' :'').'>Value 1</option>';
echo $var;
?>
atw
04-Nov-2006 01:47
04-Nov-2006 01:47
As "qbolec" states, all the notes below which use the "?" are actually references to the ternary operator (http://uk.php.net/operators.comparison").
Whilst this is kind of relevent, it probably shouldn't be in this section.
Neil
29-Sep-2006 09:08
29-Sep-2006 09:08
as skippy noted above this is very useful stuff for interspersed php & html. Here is alternative syntax example using a bitwise comparison to set checkboxes on and off to prefill a permissions bitmask calculator form:
<?
$bitmask = 481683;
?>
.... [yada yada yada]....
<input type="checkbox" name="SOME_PERMISSION_VARIABLE" value="32768" <? echo($bitmask & 32768 ? "checked" : ""); ?>>Can perform some operation<br/>
<input type="checkbox" name="SOME_OTHER_PERMISSION_VARIABLE" value="65536" <? echo($bitmask & 65536 ? "checked" : ""); ?>>Can perform some other operation<br/>
You supply a bitmask, and it prechecks all the permissions the user has so you don't need to remember what they already have to recheck them all individually.
It's much more elegant than traditional if's.
davidforest at gmail dot com
20-Oct-2005 03:26
20-Oct-2005 03:26
If you need a tidy way to do a lot of condition testing, switch statement will do the job well:
switch (true){
case ($a>0):
//do sth;
break;
case ($b>0):
//do sth;
break;
case ($c>0):
//do sth;
break;
case ($d>0):
//do sth;
break;
}
skippy at zuavra dot net
27-Jun-2005 01:32
27-Jun-2005 01:32
If it needs saying, this alternative syntax is excellent for improving legibility (for both PHP and HTML!) in situations where you have a mix of them.
Interface templates are very often in need of this, especially since the PHP code in them is usually written by one person (who is more of a programmer) and the HTML gets modified by another person (who is more of a web designer). Clear separation in such cases is extremely useful.
See the default templates that come with WordPress 1.5+ (www.wordpress.org) for practical and smart examples of this alternative syntax.
siebe-tolsma at home dot nl
18-Mar-2004 07:22
18-Mar-2004 07:22
As a rection on sttoo, if you use nested if's a bit different they are less likely to cause mistakes:
[EDITOR'S NOTE: Referenced Note has been removed]
<?php
$one = true;
$two = true;
$result = ($one ? "one" : ($two ? "two" : "none")); // $result is "one"
$one = false;
$result = ($one ? "one" : ($two ? "two" : "none")); // $result is "two"
$two = false;
$result = ($one ? "one" : ($two ? "two" : "none")); // $result is "none"
?>
i a m 4 w e b w o r k at hotmail dot com
13-Oct-2003 01:38
13-Oct-2003 01:38
Good tutorial on using alternative control structure syntax at:
http://www.onlamp.com/pub/a/php/2001/05/03/php_foundations.html?page=1
