Home

Lullabot

Lullabot Ideas

We know stuff. We empower you to know stuff too.

Drupal Module Development Deep Dive Week

London, UK
September 20-24, 2010

Learning JavaScript from PHP - a Comparison

Article by Nate HaugAugust 17, 2009 - 10:49am

This is a basic comparison between PHP and JavaScript. It's intended for users familiar with PHP and looking for JavaScript equivalents.

JavaScript and PHP Comparisons:

  • Variables
    • Scope
    • Types
    • Casting
    • NULL and empty() values
    • Booleans
    • Case Sensitivity
    • Dumping variables
  • Objects and Arrays
    • Declaration
    • Syntax
    • Associative Arrays
  • Control Structures
    • for() loop
    • foreach() loop

Variables

Variable Scope

PHP and JavaScript take two very different approaches to declaring variables. In PHP, all variables are local in scope unless declared as global. JavaScript is opposite, and all variables are global unless declared with the var keyword.

PHP

<?php
function foo() {
 
$variable_a = 'value'; // Local variable declaration.
}
function
bar() {
  print
$variable_a; // Prints nothing.
}

function
foo() {
  global
$variable_b; // Global variable declaration.
 
$variable_b = 'value';
}
function
bar() {
  global
$variable_b;
  print
$variable_b; // Prints 'value'.
}
?>

JavaScript

function foo() {
  var variableA = 'value'; // Local variable with use of "var".
}
function bar() {
  alert(variableA); // Variable not defined error.
}

function foo() {
  variableB = 'value'; // Global variable, no "var" declaration.
}
function bar() {
  alert(variableB); // alert('value')
}

An interesting twist is JavaScript also allows scoping within functions. When using the "var" declaration, variables are available for everything in the current function or any sub-functions.

PHP

function foo() {
  $variable_a = 'value'; // Local variable declaration.
  function bar() {
    print $variable_a; // Prints nothing.
  }
}

JavaScript

function foo() {
  var variableA = 'value'; // Local variable with use of "var".
  function bar() {
    alert(variableA); // alert('value');
  }
}

Variable Types

Both PHP and JavaScript are loosely typed, meaning a variable can be of any type, and change from one type to another. However both PHP and JavaScript keep track of the type of variables, and you can check this type.

PHP

<?php
$foo
= 3;
is_int($foo); // TRUE

$foo = '3';
is_int($foo); // FALSE
is_string($foo); // TRUE
?>

JavaScript

var foo = 3;
type_of(foo); // 'number'

foo = '3';
type_of(foo); // 'string'

Casting Variables

Every now and then you might need to cast variables to a specific type. This is extremely important when dealing with JavaScript's + operator, which is used for both string concatenation and for numeric addition.

PHP
In PHP, variables may be cast to certain type by using parenthesis. String concatenation is done with "." and addition with "+".

<?php
$foo
= '3.5 kg';
$bar = (float)$foo; // 3.5
$bar = (int)$foo; // 3
$baz = (string)$foo; // '3.5 kg'

print $bar + $baz; // 6
print $bar . $baz; // '33'
?>

JavaScript
JavaScript has functions specifically for casting variables to numbers. Both string concatenation and addition is done with "+". If mixing a string and a number with "+", concatenation will take precedence over addition.

var foo = '3.5 kg';
var bar = parseFloat(foo); // 3.5
    bar = parseInt(foo); // 3
var baz = '3';

alert(bar + baz); // '33'
alert(bar + parseInt(baz)); // 6

Checking for NULL or empty() values

Variables in PHP don't have to be defined for you to use them, though if you're working with E_ALL compliance on (not the default of most PHP installs), your script will throw a notice if you try to use an undeclared variable. JavaScript is a bit mixed concerning undeclared variables, if you attempt to modify or compare with an undeclared variable, the script will break entirely, but you can check the variable status using typeof() or in conditional statements containing only that variable.

PHP

<?php
// Check if a variable is declared at all.
if (!isset($foo)) {
 
$foo = TRUE;
}

// Or check if a variable has a value that equates to FALSE.
// This includes variables that have not been declared.
if (empty($bar)) {
 
$bar = TRUE;
}
?>

JavaScript

// Check if a variable is declared at all.
if (typeof(foo) == 'undefined') {
  var foo = true;
}

// Or check if a variable has a value that equates to false.
// This includes variables that have not been declared.
if (!bar) {
  var bar = true;
}

// However an undeclared variable can't be used in comparisons.
if (baz == false) { // Variable undefined error.
  var baz = true;
}

Boolean Variables

A simple but important thing to remember is that JavaScript only recognizes the keyword true in all lowercase. PHP accepts both uppercase and lowercase.

PHP

<?php
is_boolean
(TRUE); // TRUE
is_boolean(true); // TRUE
is_boolean(True); // TRUE
?>

JavaScript

typeof(true); // 'boolean'
typeof(TRUE); // 'undefined'
typeof(True); // 'undefined'

Case Sensitivity

Both JavaScript and PHP are case sensitive in their variables. PHP is not case-sensitive in function or class declarations, but JavaScript is case sensitive for these also.

PHP

<?php
// Variable case:
$foo = 'bar';
print
$foo; // Prints 'bar'.
print $Foo; // Prints nothing.

// Function case:
function foo() {
  print
'bar';
}
foo(); // Prints 'bar'.
Foo(); // Prints 'bar'.
?>

JavaScript

// Variable case:
var foo = 'bar';
alert(foo); // alert('bar')
alert(Foo); // Variable not defined error.

// Function case:
function foo() {
  alert('bar');
}
foo(); // alert('bar')
Foo(); // Function not defined error.

Objects and Arrays

In PHP, objects and arrays are two distinctly different things and have different syntaxes. In JavaScript, objects and arrays are often interchangeable, and you can switch between syntaxes freely.

Declaring an Object or Array

There are a few different ways to declare an object or an array in both JavaScript and PHP. The key difference between PHP and JavaScript is that JavaScript does not have associative arrays. Arrays in JavaScript are always numeric based. However, since objects may use array-like syntax, simply declare a new object when you'd use an associative array in PHP.

PHP

<?php
// Define an array.
$foo = array(); // New empty array.
$foo = array('a', 'b', 'c'); // Numeric index.
$foo = array('a' => '1', 'a' => '2', 'c' => '3'); // Associative.

// Define an object.
$bar = new stdClass(); // New empty object.
$bar->a = '1';
$bar->b = '2';
$bar->c = '3';
?>

JavaScript

// Define an array (longhand).
var foo = new Array(); // New empty array.
var foo = new Array('a', 'b', 'c'); // Numeric index.

// Define an array (shorthand, more common).
var foo = []; // New empty array.
var foo = ['a', 'b', 'c']; // Numeric index.

// Define an object.
var bar = {}; // New empty object.
var bar = {   // New populated object.
  a: '1',
  b: '2',
  c: '3'
};

As you might notice in the last example, declaring an object in JavaScript uses the format commonly known as JSON, which stands for "JavaScript Object Notation". JSON strings having become very popular as a faster alternative to XML, and can be read and created with the PHP functions json_encode() and json_decode().

Object and Array Syntax

JavaScript and PHP are very similar in array notation, though they differ more in their object notation. The key difference is that PHP uses an array "->" to reference items within objects, while JavaScript uses the dot ".".

PHP

<?php
$foo
= array('a', 'b', 'c'); // New numeric index array.
print $foo[0]; // 'a'

$bar = new stdClass();
$bar->a = '1';
print
$bar->a; // '1';
?>

JavaScript

var foo = ['a', 'b', 'c']; // New array.
alert(foo[0]); // 'a'

var bar = { a: '1', b: '2', c: '3' }; // New object.
alert(bar.a); // '1'

Using Objects as Associative Arrays

Let's take one more look at defining an object in JavaScript and see how it can be used to compensate for the lack of associative arrays in JavaScript.

PHP

<?php
$bar
= array(
 
'a' => '1',
 
'b' => '2',
 
'c' => '3',
);
?>

JavaScript
JavaScript doesn't have associative arrays, but defining an object works identically to an associative array in PHP.

var bar = {
  a: '1',
  b: '2',
  c: '3'
};

As mentioned earlier, in JavaScript array and object syntaxes can be mixed freely, so this new object can be referenced either as an array or an object.

// Using array syntax, even though this is an object.
alert(bar['a']); // '1'

// Or the standard object property syntax.
alert(bar.b);    // '2'

If we had a multi-level object, we can even combine the bracket and dot syntaxes.

var bar = {
  a: { red: 'my favorite', blue: 'not so bad' },
  b: '2',
  c: '3'
}

alert(bar.a['red']); // 'my favorite'
alert(bar['a'].blue); // 'not so bad'

Dumping variables

PHP

<?php
var_dump
($foo);
// Or
print_r($foo);
?>

JavaScript

console.log(foo); // Prints to Firebug or Safari console.

Logic Constructs

for()

The classic for() construct is supported nearly identically in PHP and JavaScript.

PHP

<?php
for ($n = 0; $n < 10; $n++) {
  print
$n;
}
?>

JavaScript

// Note that variables should always be
// prefixed with "var" to define a local scope.
for (var n = 0; n < 10; n++) {
  alert(n);
}

foreach()

PHP's foreach() construct can easily be converted to JavaScript's for().

PHP

<?php
foreach ($array as $key => $value) {
 
// Do something.
}
?>

JavaScript

for (var key in array) {
  // There is no "value" directly, but you can get it easily.
  var value = array[key];
  // Do something.
}

Wrap up
There are still a lot of other topics that could be covered (JavaScript is a language with a lot of tricks), but this should be a good foundation to work from. Hope you enjoy!

Comments

Milian Wolff (not verified) on August 17, 2009 - 2:31pm

Errors

Sorry, but your article has quite a few errors in it:

1) casting a string to a string doesn't change anything, hence $baz will stay '3.5 kg' and won't be '3'...

2) Functions and classes are case-insensitive in PHP! Afaik only variables and constants are case-sensitive.

3) $bar->0 or anything similar is complete nonsense and results in a parse error!

4) the differences in scope between JavaScript and PHP are much bigger than the simple stuff you mention. You should at least mention prototypes.

August 17, 2009 - 11:06pm Nate Haug

Thanks Milian

I've corrected 1-3. #4 probably applies much more to Object Orientation in JavaScript, which I figured could be an entire writeup nearly as long as this one on its own.

Anonymous (not verified) on August 24, 2009 - 2:17pm

Another tweak

Re #1 - remember to change $bar + $baz and $bar . $baz results in the example too.

Good quick summary, thanks.

Mike Caudy (not verified) on August 17, 2009 - 6:56pm

Great comparison!!

Great comparison!! This will be very useful for me and others to keep straight the syntax similarities and differences between PHP and JavaScript.

One small typo: in the JavaScript example, showing mixed usage of bracket and dot syntax, the second alert:

alert(bar['b'].blue); // 'not so bad'

gives "undefined", not "not so bad".

To get 'not so bad', the alert should be:

alert(bar['a'].blue); // 'not so bad'

Thanks for this useful writeup!

August 17, 2009 - 11:06pm Nate Haug

Thanks, great catch!

Thanks, great catch!

Mike Caudy (not verified) on August 17, 2009 - 11:26pm

There are several errors, but this is still a useful comparison

There are a number of errors, as Milian Wolff pointed out.

Here is another one:

<?php
bar
= array(
 
'a' => '1',
 
'b' => '2',
 
'c' => '3',
);
?>

"bar = array(..."
should be:
"$bar = array(..."

However, once you get the errors cleaned up, I think this will still be a useful comparison, and not just for PHP coders learning JavaScript. I came to PHP (and Drupal) from previous work with Perl and Ruby. Perl is similar to PHP with "$" for some variables (scalars, but not arrays), and Javascript is similar to Ruby, since both are OOP languages, with "." syntax. As a result, it is often hard for me to keep straight the exact syntaxes used by PHP and JavaScript, vs. these two other languages. So, I think this direct comparison between PHP and JavaScript will be useful to many people, not just PHP coders.

I encourage you to pursue this type of direct, side-by-side comparison further in future writeups.

mongolito404 (not verified) on August 18, 2009 - 2:36am

Variable Scope and Foreach Loop

As Milian Wolff said, variable scope is more than what is said. The var keyword can be used for both local and global variable. Actually, the first snippet is wrong, variableA will be defined in foo(). Since foo is defined in the same scope than variableA, it has access to it.

var variableA ='A'; // Global variable with use of "var".
function foo() {
  variableB = 'B'; // Global variable, no "var" declaration.
  var variableC = 'C'; // Local variable with use of "var".
  bar = function() {
    alert(variableA); // alert('A'), variableA is global
    alert(variableB); // alert('B'), variableB is global
    alert(variableC); // alert('C'), variableC is local to foo, but bar is defined inside foo.
  }
}
function baz() {
  alert(variableA); // alert('A'), variableA is global
  alert(variableB); // alert('B'), variableB is global
  alert(variableC); // Variable not defined error. variableC is local to foo, baz is defined outside of foo.
}
foo();
bar();
baz();

As for the foreach loop, the for..in loop is not good practice since it may return additional properties when used on real objects (as opposed to literal, JSON-like ones). Since Drupal already use jQuery, I would recommend to use it to iterate over arrays and objects. See http://docs.jquery.com/Utilities/jQuery.each

August 18, 2009 - 10:15am Nate Haug

Thanks, added

I split this into two separate examples but I've amended the scope section with the correction/extension. We'll get this article bug-free eventually. ;-)

Nathan Smith (not verified) on August 18, 2009 - 10:26am

A Few Tweaks

Great article, but I found a few issues that would be worth fixing, so that people don't get confused or come away with misinformation.

—————

First off, this is a fairly major one: In the variable scope example, the JavaScript example is inaccurate.

var variableA = 'value'; // Local variable with use of "var".

function foo() {
alert(variableA); // Variable not defined error.
}

Calling the function foo(); would actually alert the correct value. In JavaScript, all functions can see upward indefinitely to variables defined in the scope above, all the way up to global scope.

—————

Also, in the following example, the JS object ends with a comma, but it should be omitted:

var bar = { // New populated object.
a: '1',
b: '2',
c: '3',
};

scyrma (not verified) on August 18, 2009 - 12:38pm

A $ too many

In "Object and Array Syntax", there is a "$foo" in the javascript example. The '$' should not be there, afaict. :-)

Mat

TJ Holowaychuk (not verified) on August 18, 2009 - 5:48pm

Super Basic

This is just the basics.. there is FAR more you can do with JavaScript than PHP... metaprogramming is extremely rare with PHP, and even when done it is not elegant in any way.

ilessing (not verified) on August 20, 2009 - 5:45pm

thank you

This comparison write up is really handy and will prove a ready reference for me I'm sure. thank you!

rfay (not verified) on August 23, 2009 - 10:05am

IE6/7 array declarations and trailing commas

Thanks for this absolutely wonderful resource. It will help me every time I try to get my head back into js.

One big gotcha for Drupal devs is that the recommended style for array declarations in Drupal, which works great in PHP, has a trailing comma in the last element:

$x = array( 1, 2, );

The equivalent trailing comma in javascript will kill IE6 and IE7, although IE8 can handle it now.

So for IE6/7, we need in js:

var x = [ 1, 2 ];

The same applies to object declarations.

theamoeba (not verified) on August 24, 2009 - 5:40am

Thank you! Finally something

Thank you! Finally something that normal people can understand :). I have been a PHP dude for a long time now and have never really gotten into javascript, though i have wanted too. This puts it in nice terms that I can understand.

Lupus Michaelis (not verified) on August 24, 2009 - 12:33pm

Some purist adds

Hi,

In Ecmascript, and Javascript is an implementation of it, they are only one object that is global. This object is implementation defined. In browser, the global object is the window object. The objects you think globals, like location, window and so on, are properties of the global object window.

A major difference is that they are nor class nor scalar types in Javascript. Only objects exist. So said, the typeof is not well suited for checking the type information. instanceof is better, and I guess it is more efficient.

orangecoat-ciallella (not verified) on September 14, 2009 - 4:22pm

get_defined_vars for Drupal debugging

The PHP function get_defined_vars() is great for debugging.

Those new to Drupal may find the following PHP command helpful to see all variables available in the current scope:

drupal_set_message('<pre>'.print_r( get_defined_vars(), TRUE ).'</pre>' );

Looking at the XHTML source code (CTRL+U in Firefox) is usually pretty clean for viewing. If you want something really clean then install Krumo. Or, install Devel, which has Krumo built-in, and provides even deeper development debugging tools.

Similarly, you can dump/debug any variable, like $form

drupal_set_message('<pre>'.print_r( $form, TRUE ).'</pre>' );

Anonymous (not verified) on November 14, 2009 - 11:27pm

This is just the basics..

This is just the basics.. there is FAR more you can do with JavaScript than PHP... metaprogramming is extremely rare with PHP, and even when done it is not elegant in any way.

auto insurance

About this 'bot

Nate Haug

Nate Haug adds a dash of design to Lullabot. He received degrees in both a Fine Arts and Computer Science from Truman State University, creating the perfect bridge between the technical and aesthetic. Detail is his obsession, so if you know what you want, Nate will deliver your desire.

Nate joined Drupal development in 2005,...

more

Recent

Drupal Voices 160: Moshe Weitzman on Page Rendering in Drupal 7

Podcast 9.02.2010

Drupal Voices 159: John Albin Wilkins on Drupal 7 Theming

Podcast 9.01.2010

Drupal Voices 158: Emma Jane Hogbin on PHP for Designers

Podcast 8.31.2010

Command Line Basics: More Editing with Vi/Vim

Video 8.31.2010

Lullabot's Back to School Sale

Blog 8.30.2010

Popular

Drupal Voices 160: Moshe Weitzman on Page Rendering in Drupal 7

Podcast 9.02.2010

Photo galleries with Views Attach

Article 6.01.2009

Drupal Voices 159: John Albin Wilkins on Drupal 7 Theming

Podcast 9.01.2010

Drupal Voices 158: Emma Jane Hogbin on PHP for Designers

Podcast 8.31.2010

Assembling Pages with Drupal

Article 7.17.2010
 
  • Home
  • Services
  • Events
  • Ideas
  • Store

Connect the Bots:

Twitter Facebook YouTube blip.tv All Posts Newsletter
  • Ideas
  • Blog
  • Podcasts
  • Videos
  • About
  • Contact
  • Jobs
  • Services
    • Training
  • Events
    • Training Workshops
    • Other Events
    • Conferences
    • Calendar
  • Products
    • Videos
    • Books
    • Swag
  • Ideas
    • Blog
    • Podcast
    • Videos
  • About
    • Philosophy
    • Team
    • Presskit
  • Contact
    • General
    • Work Inquiries
    • Mailing List