Monday, 24 November 2014

PHP programming shortcuts: save time and lines of useless code.

Short-hand mathematical operators
Those are known by most programmers however missed by a lot, the following can be shortened by alternative next to it.

$int1 = $int1 + $int2; -- or alternatively: $int += $int2;
$int1 = $int1 - $int2; -- or alternatively: $int -= $int2;
$int1 = $int1 * $int2; -- or alternatively: $int *= $int2;
$int1 = $int1 / $int2; -- or alternatively: $int /= $int2;
Counters
Here is another very simple one, but good to know for those who don't know about it.
$int = $int + 1; -- or alternatively: $int++;
$int = $int รข€“ 1; -- or alternatively: $int--;
 Braces: you don't always need them.
if ($x)
{
echo "is x";
}
Could just be
if ($x) echo "is x";

Ternary operator
My personal favorite, saves a lot of time and I still think it makes readable code
if ($type == 'human')
{
echo 'human';
} else {
echo 'robot';
}
Or why not..
echo ($type == 'human') ? 'human' : 'robot';
You can even set variables using that method
$type_of_person = ($type == 'human') ? 'human' : 'robot';
adfasdfasd
















0 comments:

Post a Comment