Handy PHP Tips & Tricks

I have written some handy php tips and tricks right into a php file that puts them to use. You will learn some of the hidden tricks and pitfalls. Of course you would come to this file again and again unless you remember everything it contains. So here is the code with explanation:

$newline = "\n___________________________________________\n\n";
$br = "\n";

$name = 'Sarfraz';

// variable recognition in single and double quotes
print 'hello $name\n'.$br;
print "hello $name$br";

// reading string varibale as array / extracting text
print $name[3];
print $newline;

// heredoc: useful way of representing string vars. It can be handy
// in echoing out the html code or related text.
// PHP Comments inside heredocs are not applicable

$url = '/deal.php';
$text = 'Deal More Cards';
$remaining_cards = 5;

print <<< HTML
There are <b>$remaining_cards</b> cards left.

<a href="$url">$text</a>
echo $br;

// second example
$a = <<< END
Once upon a time, there was a
. ' boy!';
print $a.$br;

// third example

print <<< END
Right now, the time is
. strftime('%c') . <<< END
 but tomorrow it will be
. strftime('%c',time() + 86400);
print $newline;

// read chars from backward using negatvie start value
print substr('watch out for that tree',-6);

print $newline;

$message = <<< TEXT
The function substr_replace is useful when you've got text that's too big to display all at once, and you want to display some of the text with a link to the rest. For example, this displays the first
25 characters of a message with an ellipsis after it as a link to a page that displays more text

printf('<a href="more-text.php?id=%d">%s</a>',
       1, substr_replace($message,' ...',25));
print $newline;

// counts vowels in a given string using strstr
$string = "This weekend, I'm going shopping for a pet chicken.";
$vowels = 0;
for ($i = 0, $j = strlen($string); $i < $j; $i++) {
    if (strstr('aeiouAEIOU',$string&#91;$i&#93;)) {
print "Number of vowels are: $vowels";
print $newline;

//To reverse by words, explode the string by word boundary,
// reverse the words, then rejoin:

$s = "Once upon a time there was a turtle.";
$words = explode(' ',$s);
$words = array_reverse($words);
$s = join(' ',$words);
print $s.$br;
print $newline;

The trim functions can also remove user-specified characters
from strings. Pass the characters you want to remove as a second argument. You can indicate a range of characters with two dots between the first and last characters in the range.
// Remove numerals and space from the beginning of the line
print ltrim('10 means ten',' 0..9').$br;
// Remove semicolon from the end of the line
print rtrim('SELECT * FROM turtles;',';');
print $newline;

//Use split( ) or preg_split( ) if you need a POSIX or Perl regular //expression to describe the separator:
// regexp plus means one or more chars
$words = split(' +','This sentence  has  some extra whitespace  in it.');

foreach($words as $value)
    print $value . " ";
echo $br;
print $newline;

Helpfully, is_numeric properly parses decimal numbers, such as 5.1; however, numbers with thousands separators, such as 5,100, cause is_numeric( ) to return false.

To strip the thousands separators from your number before calling is_numeric( ) use str_replace( ):
$number = "5,100";
print is_numeric(str_replace($number, ',', ''));
print $newline;

// ==========================================
// Variable variables (IMPORTANT)
// ==========================================

You want to construct a variable's name dynamically. For example, you want to use variable names that match the field names from a database query.
$animal = 'turtles';
$turtles = 103;
print $$animal.$br.$br;

The previous example prints 103. Because $animal = 'turtles', $$animal is $turtles,
which equals 103.

Using curly braces, you can construct more complicated expressions that indicate variable names:

$stooges = array('Moe','Larry','Curly');
$stooge_moe = 'Moses Horwitz';
$stooge_larry = 'Louis Feinberg';
$stooge_curly = 'Jerome Horwitz';

foreach ($stooges as $s) {
  print "$s's real name was ${'stooge_'.strtolower($s)}.\n";
print $newline;

// This is how to capture page data before showing it to the user's browser:

$user = "Sarfraz";

$dump = ob_get_contents();
print $dump;

print $newline;

// StrPos Usage Warning

strpos() returns the location of the first substring within a string. If the
substring isn't found, strpos( ) returns false. If it is found, it returns an integer with the position. Therefore, to find a substring position, you might write:
if (strpos($string, $substring)) { found it! }

However, if $substring is found at the exact start of $string, the value returned is 0.
Unfortunately, inside the if, this evaluates to false, so the conditional is not executed.

Here's the correct way to handle the return value of strpos( ):

if (false !== strpos("hello there", "hello")) { print "found"; }

print $newline;

// open the index.php in main window / frame.
header('Window-target: main');
header('Location: index.php');


You want to force output to be sent to the browser. For example, before doing a slow database query, you want to give the user a status update.

The flush() function sends all output that PHP has internally buffered to the web server, but the web server may have internal buffering of its own that delays when
the data reaches the browser. Additionally, some browsers don't display data immediately upon receiving it, and some versions of Internet Explorer don't display a page until they've received at least 256 bytes. To force IE to display content, print blank
spaces at the beginning of the page:

print str_repeat(' ',300);
print 'Finding identical snowflakes...';
$sth = $dbh->query('SELECT shape,COUNT(*) AS c FROM snowflakes');
You want to start generating output before you're finished sending headers or cookies.

Call ob_start at the top of your page and ob_end_flush( ) at the bottom. You can
then intermix commands that generate output and commands that send headers.
The output won't be sent until ob_end_flush( ) is called:

<?php ob_start(); ?>
I haven't decided if I want to send a cookie yet.
<?php setcookie('heron','great blue'); ?>
Yes, sending that cookie was the right decision.
<?php ob_end_flush(); ?>

You can pass ob_start( ) the name of a callback function to process the output buffer with that function. This is useful for postprocessing all the content in a page, such as hiding email addresses from address-harvesting robots:

function mangle_email($s) {
    return preg_replace('/(&#91;^@\s&#93;+)@(&#91;-a-z0-9&#93;+\.)+&#91;a-z&#93;{2,}/is',


I would not like spam sent to ronald@example.com!

<?php ob_end_flush(); ?>

The mangle_email( ) function transforms the output to:
I would not like spam sent to <ronald@...>!
You want to process a variable with a period in its name, but when a form is submitted, you
can't find the variable.

Replace the period in the variable's name with an underscore. For example, if you have a form
input element named foo.bar, you access it inside PHP as the variable $_REQUEST['foo_bar'].

Because PHP uses the period as a string concatenation operator, a form variable called
animal.height is automatically converted to animal_height, which avoids creating an
ambiguity for the parser. While $_REQUEST['animal.height'] lacks these ambiguities, for
legacy and consistency reasons, this happens regardless of your register_globals


You can put a username and password in the URL if you need to retrieve a protected page. In
this example, the username is david, and the password is hax0r. Here's how to do it with
fopen( ):

$fh = fopen('http://david:hax0r@www.example.com/secrets.html','r')
    or die($php_errormsg);
while (! feof($fh)) {
    $page .= fread($fh,1048576);

// Build query string from an array

$query = http_build_query($array);


2 thoughts on “Handy PHP Tips & Tricks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s