PHP Functions to JS

Friday, June 19, 2009

Have you ever encountered a problem in coding your Javascript and can only think using the PHP defined functions as a solution?

Well you're not the only web developer who have experienced that. As a growing programmer, I know I still have a lot to learn, and one of my weakness is the Javascript.

One time, while coding the JS script, I got puzzled on how should I check if the parameter submitted to my JS function is numeric or not. Hurried to finish the task, with no second thoughts I use the is_numeric(var) syntax inside an if statement. When I tried to check the page, it of course returns an error. I review the code and realized that is_numeric() is just one of the common functions I used when coding PHP.

Since, I've been with the same kind of situations a lot of times, I Googled for an application, script, plugins etc. which could help me convert php functions to JS functions and I luckily bumped into this site http://phpjs.org/.

So what is phpjs.org is all about?

PHP.JS is an open source project in which we try to port PHP functions to JavaScript. By including the PHP.JS library in your own projects, you can use your favorite PHP functions client-side.

Using PHP.JS may speed up development for PHP developers who are increasingly confronted with client-side technology.

It also offers added functionality because JavaScript does not natively support higher-level functions such as: md5(), strip_tags(), strtotime(), number_format(), wordwrap().

PHP.JS is nothing fancy like jQuery—they're just offering PHP functions, with all of their original flaws and benefits for whomever needs them.

Here is the PHP is_numeric equivalent function:

function is_numeric( mixed_var ) {
// Returns true if value is a number or a numeric string
//
// version: 904.317
// discuss at: http://phpjs.org/functions/is_numeric
// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// +   improved by: David
// +   improved by: taith
// +   bugfixed by: Tim de Koning
// *     example 1: is_numeric(186.31);
// *     returns 1: true
// *     example 2: is_numeric('Kevin van Zonneveld');
// *     returns 2: false
// *     example 3: is_numeric('+186.31e2');
// *     returns 3: true
// *     example 4: is_numeric('');
// *     returns 4: false
if (mixed_var === '') {
    return false;
}

return !isNaN(mixed_var * 1);
}

You can download the full script at their site.

No server component required. To use PHP.JS you can either:

Kindly Bookmark and Share it: