JavaScript and PHP - Comparisons to Learn

This JavaScript article lists some comparisons between two popular web programming languages in the world of open source: JavaScript and PHP. The comparisons in this JavaScript tutorial focus on Variables, Object and Array, Control Structures; from this list, the web coders (programmers) have a look about them more accurate, and may give the appropriative solutions for the requirements of their tasks.


Sampled by © JavaScriptBank.com

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

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!

Language
Translate this page to English Translate this page to French Translate this page to Vietnamese

Recent articles
How to open a car sharing service
Vue developer as a vital part of every software team
Vue.js developers: hire them, use them and get ahead of the competition
3 Reasons Why Java is so Popular
Migrate to Angular: why and how you should do it
The Possible Working Methods of Python Ideology
JavaScript Research Paper: 6 Writing Tips to Craft a Masterpiece
Learning How to Make Use of New Marketing Trends
5 Important Elements of an E-commerce Website
How To Create A Successful Prototype For Your PCB


Top view articles
Top 10 Beautiful Christmas Countdown Timers
65 Free JavaScript Photo Gallery Solutions
Adding JavaScript to WordPress Effectively with JavaScript Localization feature
Best Free Linux Web Programming Editors
Top 10 Best JavaScript eBooks that Beginners should Learn
16 Free Code Syntax Highlighters by Javascript For Better Programming
Top 50 Most Addictive and Popular Facebook mini games
More 30 Excellent JavaScript/AJAX based Photo Galleries to Boost your Sites
Top 10 Free Web Chat box Plug-ins and Add-ons
The Ultimate JavaScript Tutorial in Web Design


Free JavaScript Tutorials & Articles
at www.JavaScriptBank.com