Archive for February, 2009

February 24th, 2009 at 8:48 pm

Implementing PHP functions in JavaScript

There are some handy functions in PHP you would sometimes like to have in JavaScript, too. Why not reimplement them? It’s not hard. Take for example in_array() and explode():

function explode(delim, val_to_split)
{
	return (val_to_split.indexOf(delim))
		? val_to_split.split(delim)
		: [val_to_split];
}
 
function in_array(needle, haystack)
{
	hlength = haystack.length;
	for (var i=0; i<length; i++)
		{ if (needle == haystack[i])
			{ return true; } }
	return false;
}

Hint: On many pages of PHP functions, there are comments which describe how to reimplement a function (e.g. PHP 4 implementations of PHP 5 functions) — in PHP though, but it’s easy to adapt them for JavaScript.