What are the Key Differences Between JavaScript and PHP?
JavaScript programmers learning PHP will find it valuable to learn the key differences between the languages. While this is not an exhaustive list, knowing these differences will help you avoid a few mistakes.
Server vs. Client Side
We can’t ignore the most obvious difference: JavaScript typically runs client-side, and PHP always runs server-side.
There are frameworks that allow JavaScript to run on a server, but JavaScript is generally considered a client-side language. Since the JavaScript engine runs in the browser, we need to understand that older browsers won’t understand newer JavaScript functions.
In contrast, PHP runs on the server so any browser will work. However, you’ll need to know which version of PHP is running on the server so you can write compatible code. You’ll also need to update your server’s PHP version, and update the code accordingly, to keep your application secure.
Combining JavaScript and PHP code allows you to manipulate data and onscreen elements with maximum flexibility. Depending on your goals, you may need to learn how to pass data between the two languages.
Console Output
Thanks to Firefox, JavaScript clients now typically provide a console window. Using the console.log() function, JavaScript allows us to print information directly to the console and avoid the main application window. This is helpful for debugging. Unfortunately, PHP does not have native Console logging capability. You may need to incorporate JavaScript or a PHP library to print to the console.
You’ll see echo used in the PHP examples below. This output will print directly to the application screen and is visible to the end user. However, you can wrap your echo contents in a <script> tag or an HTML comment to hide it from the application view.
Of course, both the console and the HTML source code windows are visible to the end user if they open a view, so be careful what you expose here.
Variables
The dollar sign $ is used to define variables and constants in many programming languages. While JavaScript accepts defining variables this way, the convention is to declare variables using var or let instead of using the dollar sign:
var a;
You can also declare a JavaScript variable as you assign a value:
var a = "something";
JavaScript variables are available to functions in descendant hierarchy. When called in a function, variables point to the original source, which can be modified:
var a = "something";
function accessA() {
console.log(a);
a = "something else";
}
accessA(); // something
console.log(a); // something else
Since PHP doesn’t have a command for declaring a variable, you’ll create it as needed:
$a = "something";
PHP variables are not available to functions unless they are passed as arguments. When called in a function, a copy is made. Modifying the copy does not affect the original resource:
$a = "something";
function accessA($x) {
echo "$x<br>"; // $x becomes a copy of $a
$x = "something else"; // this is useless
}
accessA($a); // something
echo "$a<br>"; // something
A common PHP syntax for passing an argument by reference is to use the & symbol as follows:
$a = "something";
function accessA(&$x) { // & added here
echo "$x<br>"; // now $x is actually $a
$x = "something else";
}
accessA($a); // something
echo "$a<br>"; // something else
Passing by reference using & is preferrable to converting the variable to global scope:
$a = "something";
function accessA() {
global $a; // convert to global
echo "$a<br>";
$a = "something else";
}
accessA($a);
// something
echo "$a<br>";
// something else
Using the static keyword, PHP variables created in functions persist so they can be updated with subsequent calls of the function.
function increment() {
static $counter = 0;
echo "$counter<br>";
$counter++;
}
increment(); // 0
increment(); // 1
Constants
Unlike variables, constants can’t be reassigned or redeclared.
In JavaScript, a constant is declared using the ES6 keyword const and must be assigned a value at the same time:
const a = "something";
In JavaScript, const can hold a primitive value, array, object, function, or a regular expression. The properties of the array or object can still be updated or removed. In PHP, the constant can hold a primitive value or an array.
There are two ways to declare a constant in PHP:
define("MY_CONSTANT", "something");
const MY_CONSTANT = "something";
The main differences are:
- Only the define() function works in a conditional block.
- Only const works in a class.
- define() accepts any expression, whereas const only accepts static scalar data (a number, string, bool, etc).
Hoisting
In JavaScript, variables declared with var are hoisted to the top of a script. The variable name can be used before it has been declared, and the value will be undefined. With the introduction of let and const in ES6, JavaScript now behaves more like PHP, so you’ll see an error if you attempt to use a variable or constant before it has been created using ES6 keywords.
Resources
PHP offers a special data type called a “resource.” This is a special variable (a.k.a., a handle), that holds a reference to an external resource. They are created by certain PHP functions such as:
$file = fopen("file.txt", "r");
Strings
When assigning string values in JavaScript, it doesn’t matter whether you use single or double quotes as long as you use the same mark on each end. If the value itself contains a matching quote mark, it must be escaped:
var x = "there’s no \"difference\" here";
var y = 'there\’s no "difference" here';
PHP behaves differently if you start with single quotes. It assigns the literal value (except for internal single quote marks). In contrast, when using double quotes the value is interpreted:
$x = 'Joey\’s\tbicycle.'; // stored as: Joey’s\tbicycle.
$y = "Joey’s\tbicycle."; // stored as: Joey’s	bicycle.
With double quotes, PHP will also interpret variables:
$variable = 'bicycle';
$x = 'Joey\’s $variable.'; // stored as: Joey’s $variable.
$y = "Joey’s $variable."; // stored as: Joey’s variable.
JavaScript ES6 template strings behave closer to PHP double quotes with variables interpreted correctly if you use the ${ } format:
var variable = 'bicycle';
var x = `Joey’s ${variable}.`; // stored as: Joey’s bicycle.
Spaceship Operator
This comparison operator only exists in PHP. The return value is either 1, 0, or -1 depending if one side or the other is greater:
$x = 1; $y = 2; echo $x <=> $y; // -1
else if vs elseif
It’s simple: Use else if in JavaScript and elseif in PHP.
Arrays
In both JavaScript and PHP, array items are stored as key/value pairs; however, JavaScript array keys are always numerical indexes:
var arr = ["a", "b", "c"];
console.log(arr[0]); // a
In PHP, arrays can be indexed like JavaScript:
$arr = array("a", "b", "c");
echo $arr[0]; // a
PHP also offers the associative array, which allows you to use strings for keys. The PHP associative array is more comparable to a JavaScript object:
$arr = array("pet"=>"cat", "fruit"=>"banana", "color"=>"blue");
echo $arr["pet"]; // cat
PHP doesn’t return an error if you mix and match numerical and string keys, but PHP’s array functions are intended for pure indexed or associative arrays. For best results avoid mixing indexed and associative properties in an array. Note that the numerical index count skips named indexes:
$arr = array("a", "fruit"=>"banana", "c");
echo $arr["fruit"]; // banana
echo $arr[1]; // c
Both JavaScript and PHP arrays can be nested (a.k.a., multidimensional). A nested array in JavaScript looks like:
var arr = ["a", "b", ["c", "d"]];
console.log(arr[2][1]);
// d
In PHP, a multidimensional array looks like:
$arr = array("a", "b", array("c", "d"));
echo $arr[2][1];
// d
Viewing Array Structure
As noted above, JavaScript offers the console.log() function which allows you to view information in a separate window behind the scenes. When you pass an array as an argument, it prints an elegantly formatted display of the array structure.
PHP can’t write to the console, but it offers a couple of handy functions for printing complex structures. One is print_r(), and the other is var_dump(). The former provides an easy-to-read display of the array structure. The latter provides a detailed display that includes the length of the array plus the data types and lengths of each item.
Objects
We were previously introduced to the PHP associative array above. JavaScript does not have associative arrays. Instead, it uses a Global Object class to define a collection of data with named keys. Compare the two below:
var obj = {"pet": "cat", "fruit": "banana", "color": "blue"};
console.log(obj["pet"]);
// cat
$arr = array("pet"=>"cat", "fruit"=>"banana", "color"=>"blue");
echo $arr["pet"];
// cat
Because the JavaScript object is an instance of a global Object, it does not have access to the global Array methods such as length(). Instead it has access to methods defined in the global Object.
PHP does not have a global Object like JavaScript. If the PHP associative array is not appropriate, a PHP programmer will use a class.
Classes
Both JavaScript and PHP offer ways to create classes. New for ES6, JavaScript’s class declaration allows you to create an object with prototype-based inheritance:
class MyClass {
constructor() {
this.pet = 'cat';
}
}
var instance = new MyClass();
console.log(instance.name);
// cat
In PHP, you can define a class a few ways. Here is the syntax for storing and accessing values using PHP’s standard class:
$MyClass = new stdClass();
$MyClass->pet = "cat";
$MyClass->fruit = "banana";
$MyClass->color = "blue";
echo $MyClass->pet;
// cat
Although PHP’s stdClass does not offer any built-in methods, you can add and call your own methods as follows:
$MyClass->welcome = function($arg) {
echo "Welcome " . $arg . "!\n";
};
echo ($MyClass->welcome)('Joey'); // Welcome Joey!
PHP recently introduced the anonymous class, allowing you to add properties and methods with instantiation:
$MyClass = new class {
public $pet = "cat";
public function welcome($arg) {
echo "Welcome " . $arg . "!\n";
}
};
echo $MyClass->pet;
// cat
echo $MyClass->welcome('Joey');
// Welcome Joey!
PHP gives an easy way to control access to the properties and methods in the class with public, private and other useful keywords.
Notice that the convention is to capitalize class names.
Loops
The JavaScript and PHP for, while, and do... while loop methods are coded and function similarly. If you know one syntax, you know the other.
The syntax of the forEach() method for Arrays is a little different between languages. Note that in both languages the item value must be passed and the item key/index is optional:
var arr = ["a", "b", "c"];
arr.forEach(function (value, index) {
console.log(index + ":" + value);
});
$arr = array("a", "b", "c");
forEach($arr as $key => $value) {
echo $key . ":" . $value . "<br>";
}
The JavaScript for... in and for... of methods were made for looping over objects. They don’t exist in PHP, but you can use the forEach() method on PHP associative arrays.
Functions
Javascipt and PHP both come with pre-defined methods/functions. If you are seeking a built-in JavaScript method, check references related to global Objects to see what methods have been pre-defined for the object you’re processing. For example, Mozilla’s Array documentation lists the Array methods in the sidebar.
PHP’s documentation on internal functions is extensive. If you dive deep, you can find pages like this one for string functions and this one for Array functions.
Related posts:
Helpful references:
Have feedback on this topic?