PHP’s print_r function in JavaScript

2009 February 25
by Clifford James

This function simulates the print_r function in PHP.

Download: Link.

function print_r(obj,pre,child)
{
  if(pre === undefined)   pre   = false;
  if(child === undefined) child = 0;

  var n  = "\n";
  var t  = "    ";
  var ts = "";

  if(pre) for(var i = 0; i <= child; i++) ts += t;

  if(obj.constructor == Array || obj.constructor == Object)
  {
    if(pre && child == 0)
    {
      document.write('<pre>'+n);
      document.write('Array'+n);
      document.write('('+n);
    }
    else if(pre && child > 0)
    {
      document.write(ts+'('+n);
    }
    else
    {
      document.write('Array (');
    }

    for(var value in obj)
    {
      if(obj[value].constructor == Array|| obj[value].constructor == Object)
      {
        var newChild = child + 1;

        if(pre && child == 0)
        {
          document.write(ts+'['+value+'] => Array'+n);
        }
        else if(pre && child > 0)
        {
          document.write(ts+t+'['+value+'] => Array'+n);
          newChild++;
        }
        else
        {
          document.write(" ["+value+"] => ");
        }

        print_r(obj[value],pre,newChild);
      }
      else
      {
        if(pre && child == 0)
        {
          document.write(t+'['+value+'] => '+obj[value]+n);
        }
        else if(pre && child > 0)
       {
          document.write(ts+t+'['+value+'] => '+obj[value]+n);
        }
        else
        {
          document.write(' ['+value+'] => '+obj[value]+' ');
        }
      }
    }

    if(pre && child == 0)
    {
       document.write(') ');
       document.write('</pre>');
    }
    else if(pre && child > 0)
    {
      document.write(ts+') '+n);
    }
    else
    {
      document.write(') ');
    }
  }
}

Usage:
When you want to nicely format the array with the pre tags, set true after the array parameter in the function.

var array = new Array();
array[0] = 'test0';
array[1] = 'test1';
array[2] = new Array('test2','test3');
array[3] = new Array('test4',new Array('test5','test6'));
array[4] = new Array('test7',new Array('test8',new Array('test9','test10')));

print_r(array);

print_r(array,true);

Output:

Array ( [0] => test0 [1] => test1 [2] => Array ( [0] => test2 [1] => test3 ) [3] ...

Array
(
    [0] => test0
    [1] => test1
    [2] => Array
        (
            [0] => test2
            [1] => test3
        )
    [3] => Array
        (
            [0] => test4
            [1] => Array
                (
                    [0] => test5
                    [1] => test6
                )
        )
    [4] => Array
        (
            [0] => test7
            [1] => Array
                (
                    [0] => test8
                    [1] => Array
                        (
                            [0] => test9
                            [1] => test10
                        )
                )
        )
)

Bookmark function for JavaScript

2009 February 25
by Clifford James

This is a simple bookmark function for JavaScript.

function bookmark(title,url)
{
  if(title === undefined) title = document.title;
  if(url === undefined)   url   = document.URL;

  if(window.sidebar) window.sidebar.addPanel(title,url,''); // Mozilla Firefox Bookmark
  else if(window.external) window.external.AddFavorite(url,title); // IE Favorite
  else if(window.opera && window.print) return true; // Opera Hotlist
}

Parameters are optional.

XHTML Strict Traget _blank Workaround (Update)

2008 December 30
by Clifford James

The target _blank attribute is not valid when working with XHTML Strict.
The next JavaScript example is a quick workaround to avoid an invalid XHTML page:

New:

document.observe('dom:loaded',function()
{
  $$('a[rel="external"]')).each(function(a))
  {
    a.target = '_blank';
  }
});

Old:

document.observe('dom:loaded',function()
{
  $$('a').each(function(a)
  {
    if(a.rel.include('external')) a.target = '_blank';
  });
});

When the dom is loaded we search for links. We well loop trough that searching for the value external in the rel attribute, when found we add a target=”_blank” attribute to the link.

So:

<a rel="external" href="somewhereelse">Link</a>

Becomes:

<a rel="external" href="somewhereelse" target="_blank">Link</a>

This workaround is written in JavaScript for prototype users, if you need one without using prototype just drop a comment and i’ll fix you one.

PHP’s in_array function in JavaScript

2008 October 30
by Clifford James

This function simulates the in_array function from PHP.

function in_array(needle, haystack, strict)
{
    var found = false, key, strict = !!strict;

    for (key in haystack)
    {
        if ((strict &amp;&amp; haystack[key] === needle) || (!strict &amp;&amp; haystack[key] == needle))
        {
            found = true;
            break;
        }
    }

    return found;
}

Usage:

var array = new Array('foo', 'bar', 5);

in_array('foo', array); //returns true
in_array('test', array); //returns false

in_array(5, array, true); //returns true
in_array('5', array, true); //returns false while checking strict because 5 is an integer and not a string

Delete item from array

2008 October 30
by Clifford James

This is a function for deleting one single item or an array with items from an array.

function array_delete(&amp;$array, $key_to_be_deleted)
{
    $new = array();

    if(is_string($key_to_be_deleted))
    {
        if(!array_key_exists($key_to_be_deleted, $array)) return;

        foreach($array as $key =&gt; $value) if($key != $key_to_be_deleted) $new[$key] = $value;

        $array = $new;
    }

    if(is_array($key_to_be_deleted)) foreach($key_to_be_deleted as $del) array_delete(&amp;$array, $del);
}

Usage:

array_delete($array, 'item')

Modules and clean URLs with PHP and .htaccess

2008 October 16
by Clifford James

In this post i explain how to make a modulair system with clear urls with PHP and .htaccess.

Folder setup:

index.php
.htaccess
/configurations
    /modRewrite.php
/modules
    /home
        /index.php
    /test
        /index.php
        /page.php

Explanation:
Pretty self explaining, all of the configuration files are been put in the configurations folder and modules goes in the modules folder.

.htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/%{REQUEST_URI} [QSA,L]

Explanation:
RewriteEngine On: Turns on the RewriteEngine.
RewriteCond %{REQUEST_FILENAME} !-f: If the requested file excists, use it.
RewriteCond %{REQUEST_FILENAME} !-d: If the requested folder excists, use it.
RewriteRule ^(.*)$ index.php/%{REQUEST_URI} [QSA,L]: Everything gets redirected to index.php

/configurations/modRewrite.php

if(isset($_SERVER['PATH_INFO']))
{
  $parameters = explode('/', $_SERVER['PATH_INFO']);

  array_shift($parameters);
}

if(count($parameters) > 1)
{
  foreach($parameters as $key => $parameter) define('item'.($key + 1), $parameter);
}
  elseif(count($parameters) == 1)
{
  define('item1', $parameters[0]);
  define('item2', 'index');
}
else
{
  define('item1', 'home');
  define('item2', 'index');
}

Explanation:
With $_SERVER['PATH_INFO'] we grab everything on the right side of the hostname, example: domainname.nl/test/page -> /test/page.
Next we split that up on the / explode('/', $_SERVER['PATH_INFO']) so we’re getting an array like this: Array ( [0] => [1] => home [2] => page ). We don’t need the first parameter so we remove that one with array_shift($parameters).
After that we’re going to define some constats we can use in our code, these are item1, item2, etc…

index.php

require_once('/configurations/modRewrite.php');

include('/modules/'.item1.'/'.item2.'.php');

Explanation:
Pretty self explaining again, loads the configuration file modRewrite and loads the given module.

Usage:
www.domainname.nl -> /modules/home/index.php
www.domainname.nl/test -> /modules/test/index.php
www.domainname.nl/test/page -> /modules/test/page.php
www.domainname.nl/test/page/7 -> /modules/test/pagie.php the 7 we can use as and id for page numbering for example.