There are a lot of php tips or tricks that you may don’t know. So I want to share with you with tips that I know. Some of them can help a lot and some of them are to write less code. Here is a list of tips and tricks:
1. Did you know you can write a variable in a string with double quote and php will print it as variable?
$variable = 'ADD ME';
$text = "So here is $variable and some text";
echo $text; // output: So here is ADD ME and some text
//other method with brackets
$variable['add'] = 'ADD ME';
$text = "So here is {$variable['add']} and some text";
echo $text; // output: So here is ADD ME and some text
2. Did you know what is difference between quote (‘) and double quote (“) in php (look at $text)?
$variable = 'ADD ME';
$text = 'So here is $variable and some text';
echo $text; // output: So here is $variable and some text
$variable = 'ADD ME';
$text = "So here is $variable and some text";
echo $text; // output: So here is ADD ME and some text
3. Did you know how to write shorter IF/ELSE ?
//original
if($hey){
echo 'hey';
}else{
echo 'bye';
}
//short method
echo ($hey)?'hey':'bye';
4. Did you know you can assign variable and check in IF statement at the same time with one = ?
if($ok = $this->getOk()){
echo $ok; //if $ok is not empty or false it will echo $this->getOk() value
}
5. Did you know you can create a function on the fly ( http://lt.php.net/create_function )?
$sumfunction = create_function('$a,$b', 'return $a + $b;');
echo $sumfunction(3, 2); //output: 5
6. Do you know that true === 1 is equal to false, because === is not the same as == ?
if(true === 1) //will result in false
if(true == 1) //will result in true
//because === will check type also
7. Do you know that @ near variable will suppress php warning messages ?
echo $variable; //will result in warning message, because $variable is not defined
echo @$variable; //no warning message
8. Do you know that echo is faster than print and quote is faster than double quote ?
I will add some more tips and tricks later.