Over the years I’ve come across some useful tricks in PHP that are not obvious, but are worth mentioning. This is not meant to be a comprehensive list of all the useful tricks that you can do with PHP.
1. Count Characters in a String
To do this, I’ve usually just used the function
strlen(). However, there is a faster method. Take a look at the following code example:
<?php $string = 'testing'; if(isset($string)) echo "The string '$string' is at least 7 characters long."; else echo "The string '$string' is less than 7 characters long.";
You treat the
$stringvalue like an array by passing an integer value to
isset(). If that number plus one is greater than or equal to the number of characters in the string, it will return true. You need to add one because it is zero based.
2. Use PHP
Echolike a Function
I’ve always thought that if you wanted to concatenate strings with
echo, you needed to use periods. But you can actually treat
echolike a function and use commas instead (it is also faster). Take a look at the following code:
<?php $string1 = 'test-string1'; $string2 = 'test-string2'; $string3 = 'test-string3'; echo 'String #1: ', $string1, '<br />'; echo 'String #2: ', $string2, '<br />'; echo 'String #3: ', $string3, '<br />';
3. Use Single Quotes When Possible
By using single quotes instead of double quotes, you save PHP from having to parse your string for variables. It not only is faster, but I find it more programmer-friendly because it is easier to find variables in your code.
Also, when referencing an array that has a string index, always use single quotes. This prevents PHP from having to figure out exactly what you were trying to say.