Best PHP 101 Function

I was explaining to a friend the other day how to best debug PHP scripts.  There are of course debugging modules that can be bolted in or other specialty IDE tools.  However, since this guy was new to the language and to programming in general I figured I would cut all of that out and make it simple and easy. With PHP the alternative is to dump information out to the screen and read it from there. I shared with him my all time favorite, most used, yet simplest PHP function for doing this.  It looks something like this:

function pa($array){
    print "<pre>";
    print_r($array);
    print "lt;/pregt;";
}

If you know anything about PHP and HTML you of course know what that is and does.  If you’re just starting out commit it to memory as it will save you a ton of time as you learn to work with arrays.  To dissect the script line by line we first start with the function declaration.  I call the function “pa” for print array.  It’s easy for me but use whatever is easy to remember and easy to type because you will use this often.  The $array variable is of course the array we want to blow apart to get a full look at.  Next,  we “print” the first “pre” formatted text html tag.  Next comes the array data.  Finally, we close the HTML “pre” tag and wrap up the function.

To implement this function I throw the code above at the beginning of the file I am working with or in a file that’s included first thing when the script runs.

Below is an example of the code usage along with the output.

function pa($array){
	print "lt;pregt;";
	print_r($array);
	print "</pre>";
}
 
$a = array ('a' => 'microsoft', 'b' => 'apple', 'c' => array ('centos', 'ubuntu', 'gentoo'));
 
pa($a);

The output will then be formatted like you see below:

1
2
3
4
5
6
7
8
9
10
11
Array
(
    [a] => microsoft
    [b] => apple
    [c] => Array
        (
            [0] => centos
            [1] => ubuntu
            [2] => gento
        )
)

As you can see, nothing earth shattering, unless of course, you have never seen something link this before. Honestly, I really don’t enjoy programming so anything I can do to make it easier on myself… I will do it! I hope this has made someone else’s life easier as well.

This entry was posted in PHP and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.