Something that really would like to know but never found out are shortcuts in PHP.
I am currently coding a function with a foreach
loop with just a sing
You can use it for simple things like:
if($a === true) continue;
But for some more complicated sub-conditions it may cause you problems:
$a = false;
$b = false;
if ($a === true)
if ($b === true)
echo 1;
else
echo 2;
With the code above, you would expect to see "2" as output, but you won't.
It will work fine if you only have one argument inside!. But if you want to omit curly brace you can use colon and end. example:
if(a < 1 ) :
echo "a is less than 1";
else :
echo "a is greater than 1";
endif;
When you omit the braces it will only treat the next statement as body of the condition.
if ($x) echo 'foo';
is the same as
if ($x) { echo 'foo'; }
but remember that
if ($x)
echo 'foo';
echo 'bar';
will always print "bar"
Internally it's the other way around: if
will only look at the next expression, but PHP treats everything in {}
as a single "grouped" expression.
Same for the other control statements (foreach
, and so on)
The answer is easy. This is the same in C/C++.
if, if/else, if/else if/ else and loops => If the next statement is one single line, you can omit the curly braces.
Ex:
for($i= 0; $i<=100; $i++)
{
if($i % 7 == 0)
{
echo $i . "<br>";
}
}
It can also be written in this way:
for($i= 0; $i<=100; $i++) if($i % 7 == 0) echo $i . "<br>";
There are places where you can, but you never should.
Explicit is always better than implicit.
Who knows when you're going to have to go back and modify old code. It's so easy to miss that stuff and there's nothing gained by doing it.
When can I omit the curly braces and in which structure/loop/function? I know that I can definitely do so in if and else. But what about while, for and foreach?
For If/else it is possible to have single and multiple statements without curly braces by using the following construct:
<?php
if ($x):
echo 'foo';
echo 'bar';
else:
echo 'nofoo';
echo 'nobar';
endif;
?>
As described in this answer
For while, for and foreach, only single statements are allowed without curly brackets
<?php
foreach($array as $x => $y)
$do_something = $x;
?>