If, else, while and switch statements PHP
When developing applications you want to keep in mind that even though they might seem unimportant
when keeping the loadtime to a minimum they can have quite an impact on your server.
If
The standard way to perform an if ... else statement is pretty straightforward.
if($myvalue == 10)
{
$x = "the value is 10";
}
else
{
$x = "the value is not 10";
}
This code looks rather cluttered, luckily there is a way to express the same statement in only one line.
The one line if statement is also known as the ternary operator if you want to look it up in the PHP documentation.
It has also been called the short if statement and the one line if statement.
Here is an example of the short if statement :
$x = ($myvalue == 10) ? "the value is 10" : "the value is not 10";
In the line of code above, if the value of the string x is equal to 10, the string "the value is 10" is printed out.
If the value of the string x is anything other than 10, the string "the value is not 107" is printed out.
Switch
I would recommend everyone to use switch in case there is a need for more than two if statements in the same code.
Switch is faster due to it's ability to end the proces of checking other cases once a case has been matched.
The switch statement is also very clean and simple in comparison to if ... else.
Here's an example :
$myvalue = 5;
switch($myvalue)
{
case 1 :
echo "the value is 1";
break;
case 5 :
echo "the value is 5";
break; // the processor will stop the switch statement here and continue processing
case 10 :
echo "the value is 10";
break;
}
// after finding a matching case PHP will continue processing here...
We can even use the beautiful PHP switch statement to check mutiple values very fast like this :
$myvalue_a = 5;
$myvalue_b = 1;
switch(true)
{
case ($myvalue_a == 5) :
echo "the value A is 5";
break;
case ($myvalue_b == 1) :
echo "the value B is 1";
break;
}
The true boolean in the previous example makes sure the switch doesn't need an input to match but
will just check each case statement individually.
While
I recently read an interesting article about the regular while loop versus the do-while loop.
The while loop is a little bit slower than the do-while loop, so I recommend using the do-while loop instead.
here's an example of the normal while loop :
$counter = 1;
while($counter < 99)
{
++$counter;
}
This example keeps incrementing the integer counter by ++var, you can also use var++ which in my PHP
experience seems to be a little bit slower.
$counter = 1;
do
{
++$counter;
}while($counter < 99);
Testing different approaches to building PHP code is always good, another important fact is that you can
write faster performing code when you realise how PHP functions actualy work. Always keep in mind that
PHP processes after one another and you have to find the perfect balance between neat code and fast
execution according to your specific needs and wishes.
Posted by James on 2009-05-06 in the category " php "
