PHP Reference Book Blog

PHP Reference: Beginner to Intermediate PHP5

Archive for the ‘Tips’ Category

Apr-14-09

Use isset() Instead of strlen()

posted by Mario Lurig

This tip is courtesy of a great article, 10 Advanced PHP Tips Revisited

When referencing an array’s value via a numeric key, you follow the variable name ($variable) with the numeric index, enclosed by square brackets [5]. e.g. $variable[5] = ‘value’
However, when $variable represents a string, using the same syntax will return a string with the character at the position specified by the numeric index (0 marks the first character in the $variable string). An example:

$string = 'abcdefg';
var_dump($string[2]);

Output: string(1) “c”

Where this comes into play is when using isset() rather than strlen(). Consider the following example:

$string = 'abcdefg';
if (isset($string[5])){
  echo $string[5].' found!';
}

Output: f found!

$string = 'abcdefg';
if (isset($string[7])){
     echo $string[7].' found!';
  }else{
     echo 'No character found at position 7!';
}

Output: No character found at position 7!

This is faster than using strlen() because, “… calling a function is more expensive than using a language construct.” It’s little tricks like this that will keep your code lean and efficient. Thanks to Chris Shiflett and Sean Coates for their contributions to the referenced article.

Tags: ,
Jan-12-09

Display a Query String Value on a Web Page

posted by Mario Lurig

It seems simple, almost basic, but many people want to display the contents of a query string on a page for the user or just for troubleshooting purposes. Everyone does it, everyone needs to do it, and there are a few different options I’m going to introduce below. First, our sample URL:

http://www.phpreferencebook.com/?variable=value&name=Mario%20Lurig&gender=male%21

or

http://www.phpreferencebook.com/?variable=value&name=Mario Lurig&gender=male!
  1. Display the whole string (everything after the question mark)
    • <?php echo $_SERVER['QUERY_STRING']; ?>
      • variable=value&name=Mario%20Lurig&gender=male
  2. Display the whole string decoded (convert %## to original characters)
    • <?php echo urldecode($_SERVER['QUERY_STRING']); ?>
      • variable=value&name=Mario Lurig&gender=male!
  3. Show each variable and value as an array (already decoded)
    • <?php print_r($_GET); ?>
      • Array ( [variable] => value [name] => Mario Lurig [gender] => male!
    • <?php echo '<pre>'; print_r($_GET); echo '< /pre>'; ?>
      • Array
        (
            [variable] => value
            [name] => Mario Lurig
            [gender] => male!
        )
        

There are lots of options from there, so don’t let this be the end of your exploration of how to display a query string value on a page. If you have any great tricks, feel free to share them in the comments below!

Nov-30-08

Strip_tags() – Less Than you Bargained For

posted by Mario Lurig

While this may be handy for removing HTML from a string, be forewarned that the function is a lot less picky than you may think when it comes to the less than symbol ( < ). First, the section from the PHP book:


strip_tags($string [, allowed_tags])

allowed_tags – [optional] $string

Remove HTML tags and comments from $string. If specific tags should be
excluded, they can be specified inside allowed_tags.

Examples:
$string = "<p>This is a paragraph. </p><strong>Yay!</strong>";
echo strip_tags($string), strip_tags($string, '<p>');

HTML Source Code:

This is a paragraph. Yay! <p>This is a paragraph. </p>Yay!


So what happens to the following example, when we want to remove all the tags? Fair warning, something strange happens:

$string = "I <strong>love</strong> this book because it costs <$20.";
echo strip_tags($string);

HTML Source Code:

I love this book because it costs

As you can see, it removed the <$20 portion of the string as well, even without the closing greater than ( > ) tag at the end. Be careful when using strip_tags(), especially without specifying the allowed tags, or consider using an alternate such as htmlspecialchars() to encode the characters into their html equivalent rather than removing them.

Sep-15-08

Display all PHP Errors and Warnings

posted by Mario Lurig

Every time I was debugging my pages I found myself searching around for this little chunk of code to display PHP errors. So, I put in the book so it was always nearby. Since people still search google endlessly, I thought I would provide it here as well. If you wish to see all the PHP errors and warnings in your script, include the following bit of code:

error_reporting(E_ALL);
ini_set('display_errors', '1');

Now, continue to beat your head against your keyboard while you continue to hunt down your missing semicolon or closing parenthesis.

Aug-1-08

Formatting Characters

posted by Mario Lurig

We’ve all seen them:

  • \n – new line
  • \r – carriage return
  • \t – tab
  • \b – backspace

But many wonder when to use them or more specifically, why they aren’t working as expected. So let’s address the basic usage and rules.

Rule #1: When using a formatting character in your code, it must be within “double quotations” otherwise it will be taken as a literal backslash and letter.

When do you use it? When writing to a file with fwrite() or file_put_contents(), sending a text email with mail(), or when adding formatting to pre-populated data in the form element <textarea>. Now, notice I made no mention of HTML output directly. While it’s possible to represent new line, tab, carriage return in HTML if it is within the preformatted tags <pre></pre>, in most cases these tags are not present and HTML will ignore these formatting characters.

Rule #2: Not all computer systems obey the formatting characters the same. When using \n (new line), also include a carriage return (\r) character.

So what do you do if you have a paragraph, for instance submitted by a <textarea> form, that is preformatted and want it to display in the HTML with the \n (new line) breaks represented? That’s when you toss the string into the function nl2br(), which changes all \n to the xhtml line break <br />.

Example:

echo nl2br("Hello\n\rWorld\n\r!!!");

Results:

Hello
World
!!!