3 Tips for a Quick and Clean PHP
This post will be all about a few tip for a quicker and cleaner php code, maybe most of you know it already but i would like to share it with all anyway :)
Get rid of simple If ... else
if you use an "if .... else" statement just make a decision on a value or return a value like so :
<?php
if($accessLevel = 100){
$isAdmin = true;
}
else {
$isAdmin = false;
}
If this is all you need using an If statement then get rid of it :D , you got a better, cleaner and shorter way to do so , which is "Ternary Operator", and here is how it looks like :
<?php
$isAdmin = ($accessLevel == 100) ? true : fasle;
As you can see, it's pretty simple, isn't :) ?
Btw ... since you can assign the value using ternary operator then you can also use it to return a value like so :
<?php
function isAdmin($accessLevel)
{
return ($accessLevel == 100) ? true : false;
}
Simpler Array Declaration
Who doesn't use and mess with Arrays every single coding day :D ?? almost no one.
Well can we declare an Array and give it some values?? come on, we all do
<?php
$names = array('Sam',);
This is the traditional way of declaring an Array, but thanks to PHP specially version 5.4 we go a lovely nicer way to do the same as follow :
<?php
$names = ['Sam', 'Adam', 'Joly', 'Bob'];
Yes i know, Just square brackets ( [ ] ) and no keywords anymore :)
String Replacement
If you wanna just replace simple string with another then always make sure to use strreplace() over pregreplace() , if you wonder why i can tell you that it's not secret that string functions are much faster than RegularExpressions ones, so when you don't need a pattern then don't use RegEx , for Example :
<?php
echo str_replace('oo', '00', 'book'); //will print b00k
of course if you need a pattern then use RegEx :)
this is all for now, there is may more tips but i'll share it on another posts to keep each one simple and easy to read :)
Good Luck.
Written by Samer Moustafa
Related protips
2 Responses
You can use just
$isAdmin = ($accessLevel == 100);
without any operations
Sure it could be, but it's just an example for clearness, it could be any other data type which will need a specific assignment :)