Wednesday, March 23, 2016

Some Useful PHP Tricks You May Not Know

After I read many articles, I found some cool tricks in PHP that are very useful for our projects. Please have a look at 5 tricks below you may satisfy with them.



1. Array in Form Fields

Not only the form input fields that create array like
<input name="name['fullname']">
but you can create arrays with checkboxes also.

<label><input type="checkbox" name="hobbies[]" value="Sports" /> Sports</label><br />
<label><input type="checkbox" name="hobbies[]" value="Hiking" /> Hiking</label><br />
<label><input type="checkbox" name="hobbies[]" value="Swimming" /> Swimming</label><br />
<label><input type="checkbox" name="hobbies[]" value="Swimming" /> Watching Movies</label><br />

2. Count Character in a String

When you want to count the string you will think about strlen() function. However, we have a fastest way to count it. Take a look at the following code:

$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 treated $string like an array.

3. Use PHP Echo like a Boss

Most of the time we always thought that if we want to concatenate strings with echo, we need to use period. But we can use echo like a function that can replace period with commas instead. Please look at the fastest way to do so:
$string1 = 'test-string1';
$string2 = 'test-string2';
$string3 = 'test-string3';

echo 'String #1: ', $string1, '
'; echo 'String #2: ', $string2, '
'; echo 'String #3: ', $string3, '
';
You will find some more useful trick anywhere else, but these cool tricks is for you. Good luck!

0 comments:

Post a Comment