Justtechjobs.com Find a programming school near you






Online Campus Both


Six Cool PHP Tricks You May Not Know

by chrisroane

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[6]))
	echo "The string '$string' is at least 7 characters long.";
else
	echo "The string '$string' is less than 7 characters long.";
You treat the $string value 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 Echo like 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 echo like 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.
[ Next Page ]


Comments:
Be carefull with isset($str[6])thx405/17/10 02:50
http://chr.ishenry.comChris Henry05/13/10 00:50
Thanksrazvantim05/03/10 03:41
3. Use Single Quotes When Possiblemario04/29/10 08:22
wut wat wotwut04/29/10 03:57
Single quotes.MikeFM04/29/10 01:31
pagesJoe04/27/10 09:21
5. Use Arrays in Form FieldsNick04/24/10 22:42
Variable VariablesWebDevHobo04/23/10 10:14
strlen is betterBk Iyer04/22/10 14:31
HandyGaui04/22/10 14:08
HandyGaui04/22/10 14:06
 

If you are looking for help, please post on the appropriate forum here. Your questions will be answered much more quickly.

Add A Comment:

Name:

Email:

Subject:

Message:

To reduce spam posts, messages are now manually approved

You are not [logged in]. That means your account will not get credit for this post.