Feb 18

The most useful php functions EVER!

Tag: php,Tutorialserm @ 6:56 pm

Many times when you’re writing a php script, you need to put things in arrays.

You might be thinking to yourself why doesn’t this section of code work?

Well let me introduce you to my little friend print_r() and is big brother var_dump().

These 2 functions can save you hours of frustration, and also keeps you from looking like a total lamer in ##php.

Here’s some code taken from php.net if you didn’t check out the link to print_r.

<pre>
<?php
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z')); print_r ($a); ?> </pre>

Outputs:

<pre>
Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )
)
</pre>

The great thing about print_r() and var_dump() is they work with objects as well.

Since you are more than likely a newbie at coding in php, let me explain a little more in depth as to why this is so important.

Let’s say you’re building a site with a form.

<form method="post">
  <input type="text" name="foo">
  <input type="submit" name="action" value="Send">
</form>

After you submit it where did the data go, what is it doing? How is it formatted?

Well that’s where print_r() and var_dump() come into play.

When you are writing a page add this code to the bottom of the page:

<b>$_GET</b>
<pre>
  <?php print_r($_GET); ?>
</pre>
<b>$_POST</b>
<pre>
  <?php print_r($_POST); ?>
</pre>
<b>$_SESSION</b>
<pre>
  <?php print_r($_SESSION); ?>
</pre>

After you do that you can get a pretty good idea of what’s going on inside your page while you’re codeing it. You can also do this with objects as well.

I mentioned to someone in ##php that if I ever wrote a manual print_r() and var_dump() would be the on the first page. They said not to forget about debug_backtrace() This is a nifty function indeed.

I hope this helps you look less like a lamer in ##php and more like a knowledgable programmer. I use print_r so much I even wrote these 2 functions to help me out.

<?php
function ent($string) {
    if (is_array($string) || is_object($string)) {
        return '<pre>'. htmlentities(print_r($string,true),
                              ENT_QUOTES).'</pre>';
    }
    return htmlentities($string, ENT_QUOTES);
}

function eent($string) {
    echo ent($string);
}

?>

Happy Coding,
Erm

Leave a Reply

You must be logged in to post a comment.