PHP and JavaScript are both scripting languages that web developers use frequently. But each has its own nuances and use cases.
In this post, we’ll explore the differences between the two, and when you should use each language in development projects.
Let’s begin by looking at how these languages came into being.
Prefer to watch the video version?
PHP vs JavaScript: Origins
PHP is an open source language created in 1995 by Rasmus Lerdorf. The name came from Personal Home Page Tools — a set of scripts used by Rasmus to track visits to his site.
With the launch of PHP 3.0, the language got a reverse acronym: PHP: Hypertext Preprocessor. It’s simply known as PHP now.
JavaScript was created in 1995 by Brendan Eich of Netscape to bring interactivity to the Web. Originally known as Mocha, the name was changed to LiveScript, and later JavaScript to take advantage of the Java language’s popularity.
Today JavaScript is officially known as ECMAScript, but JavaScript is what most people still call it.
So, both languages have been around for some time.
Now we’ll look at some of their other similarities.
PHP and JavaScript Similarities
Language Type
PHP and JavaScript are both scripting languages. This is as opposed to ‘pure’ programming languages such as Java or C++.
Scripting languages tend to be interpreted rather than compiled. That means they are translated into machine code via a third party rather than directly. This has an impact on their runtime.
Think of it this way: imagine you want to translate a web page from your native language into Navajo. If you didn’t know the Navajo language you’d need an interpreter to help you, and the translation would take more time.
This is why compiled languages tend to be faster than interpreted languages.
Typing of Variables
Another commonality is that PHP and JavaScript are weakly typed.
This means that when you create a variable in either language, you do not need to assign its data type: it is assumed.
So, you can write the following in PHP:
$x = 'Hello world';
$y = 'Bonjour le monde';
Or in JavaScript:
var x = 'Coding is fun';
let y = 'No, honestly';
In both languages, these variables will be recognized as strings (sets of characters).
This is opposed to a strongly typed language like Java, where you must say what type of variable you are using when you declare it:
int x = 5;
Both PHP and JavaScript are dynamically typed: in other words, you can change the type easily by redefining it in your code:
$x = 5;
In PHP, $x is now an integer.
x = 3.14195;
In JavaScript, x is now a number.
Because types aren’t defined explicitly in PHP or JavaScript, you need functions to tell you what data type you are working with.
JavaScript has the typeof function to do this.
PHP has the gettype function to return a variable’s type. A new, improved version of gettype, get_debug_type, is part of the PHP 8 release.
Classes and Objects
Neither PHP nor JavaScript were originally object-oriented. Object orientation was added to them as the languages evolved.
The ability to create objects and classes came in with PHP 5, in 2004.
JavaScript did not use objects or classes until much later. They came into the language in 2015, with ES6’s introduction.
A class is a generic grouping of objects.
An object is an entity with properties (characteristics) and methods (behaviors).
The game Dungeons and Dragons (D&D) provides a good analogy.
A player character corresponds to an object. Each character belongs to a character class, such as a Barbarian, Rogue, or Wizard.
Objects can have any number of properties that you care to define.
So, a character’s properties may include:
- name
- race
- abilities (Strength, Intelligence, Wisdom, Dexterity, Constitution, and Charisma)
- personality type (e.g. bold, timid, curious)
- alignment (lawful, chaotic, good, evil)
You can use object methods to retrieve information about the object.
Here is a PHP code example of a class and object definition:
<?php
class Sorcerer {
// Define properties
public $name;
public $race;
public $intelligence;
// Constructor function for the object
// takes 3 arguments, name, race and intelligence
function __construct($name, $race, $intelligence) {
$this->name = $name;
$this->race = $race;
$this->intelligence = $intelligence;
}
# Define object methods
// Get the name
function get_name() {
return $this->name;
}
// Get the race
function get_race() {
return $this->race;
}
// Get intelligence
function get_intelligence() {
return $this->intelligence;
}
} // end Sorcerer class
// Create a Sorcerer
$yensid = new Sorcerer("Yen Sid", "Human", 18);
# Output the object properties in the browser
echo $yensid->get_name();
echo "<br>";
echo $yensid->get_race();
echo "<br>";
echo 'Intelligence: ';
echo $yensid->get_intelligence();
?>
When this code is added to an HTML file, the output in the browser should be the following:
Yen Sid
Human
Intelligence: 18
You can also define methods which are actions that the objects take, or have performed on them.
In D&D, they might be:
- surpriseAttack()
- disarmTrap()
- castSpell()
- resistPoison()
When a method is run on an object, the outcome may be dependent on the object’s properties. Hence a sorcerer’s apprentice object will not be able to cast spells as effectively as a seasoned wizard object.
Market Demand
Another thing that PHP and JavaScript have in common is that developers for both languages are in high demand.
Developers using JavaScript and PHP are also well compensated.
In the USA, they make an average of around $80,000 a year.
Documentation
The less good news for newcomers to PHP or JavaScript is that the official documentation for both languages is not very user-friendly. It’s been written for experienced developers rather than beginners.
You can check out the documentation for each language here:
JavaScript teacher Chris Ferdinandi laments the lack of good JavaScript documentation, saying that it was one of the reasons it took him so long to master the language.
At this point, you might be wondering, “What is the difference between PHP vs JavaScript?” Actually, there are several.
What Are the Differences Between PHP vs JavaScript?
Server-Side vs Client-Side Scripting
PHP is a server-side scripting language. This means that it runs on the web server as opposed to a client machine.
Server-side programming is useful for delivering dynamic content (typically from a database) to users, such as a welcome message (“Hi, Claire!”) when a user logs in.
More seriously, server-side scripting is used in ecommerce. For example, there are over 100 WooCommerce extensions that connect via APIs (application programming interfaces) to different payment providers to process transactions.
JavaScript is a client-side language, so it runs on a user’s laptop, phone, or tablet.
JavaScript can manipulate the DOM which stands for Document Object Model and you could think of it as a tree-like structure formed from the HTML of a web page.
If you have ever come across an accordion or toggle, perhaps as part of a FAQ plugin, you’ve seen client-side JavaScript in action. When you click or tap on a question, JavaScript event handlers toggle the CSS display or visibility properties on or off, showing or hiding the relevant answer.
Frontend vs Backend
PHP runs in the backend of a website — the part that visitors do not see! In WordPress, this means that PHP does all its work on the web server and in the WordPress admin.
JavaScript traditionally ran on the frontend, but that changed in 2009 when Node.js, a backend runtime, was launched. Today JavaScript is truly a full stack language.
Combination with Other Languages
With PHP being a backend language, it’s part of the LAMP stack (Linux, Apache, MySQL, PHP).
PHP can merge with HTML. You will see this by examining the code for many web apps, including WordPress.
Here is an example from the Twenty Twenty theme index.php file:
<header class="archive-header has-text-align-center header-footer-group">
<div class="archive-header-inner section-inner medium">
<?php if ( $archive_title ) { ?>
<h1 class="archive-title"><?php echo wp_kses_post( $archive_title ); ?></h1>
<?php } ?>
<?php if ( $archive_subtitle ) { ?>
<div class="archive-subtitle section-inner thin max-percentage intro-text"><?php echo wp_kses_post( wpautop( $archive_subtitle ) ); ?></div>
<?php } ?>
</div><!-- .archive-header-inner -->
</header><!-- .archive-header -->
However, if you mix PHP with other backend languages in web apps it’s harder to maintain them. Plus, you not only have to know PHP, you have to study and be competent in those other languages as well!
JavaScript developers have a bit more freedom in writing their code. They can use the language with HTML, XML, and Ajax.
Case Sensitivity
Case sensitivity is the distinction between upper and lowercase letters when naming entities in the language.
PHP is partially case sensitive. Case matters for some things and not others.
PHP variables are case sensitive.
So if you create a variable in PHP:
$dog = "chihuahua";
and try to get the value of $DOG later on in your code, it won’t work.
PHP functions, however, are case insensitive.
If you create this function in PHP:
function dogFetch() {
// your code to run when the function is called
}
and later call DogFetch() in your code, your function will still run.
However, this is not good coding practice, as it is inconsistent.
JavaScript, on the other hand, is completely case sensitive. So variables called beagle, BEAGLE, and Beagle would all be distinct from one another.
Syntax
Syntax is the set of rules that govern a language. That includes word order, grammar, and punctuation.
In English, we might say:
I ate my soup slowly.
But if you were Yoda, you would say this:
My soup slowly I ate.
Why? The syntax is different. Same words, different order.
Some languages use words that appear the same, but they have a different meaning.
While humans are forgiving if we use the wrong word, computers are very literal. If we make a mistake in our programming syntax, a computer often doesn’t know what we meant, which usually results in an error.
With JavaScript and PHP, they both have the same double forward slash syntax for single-line code comments:
// This is a comment
But PHP also has another form of comment syntax:
# This is a comment
If you try to use PHP comment syntax in JavaScript, you get an error:
# This is a Comment
Uncaught SyntaxError: private fields are not currently supported
Other syntax errors are common to both JavaScript and PHP, such as:
- Missing a semicolon (;) at the end of a line of code.
- Not using a pair of curly braces {} for conditional statements.
Variable and Constant Definitions
As we saw earlier, JavaScript and PHP have different ways of declaring variables.
They also define constants differently.
JavaScript uses this syntax:
const x = 6;
For a simple constant like this, its value can’t be changed later on.
Whereas PHP uses the define() function for constants.
define(name, value, case-insensitive)
By convention, PHP constants are styled in uppercase. An example is:
define('MONSTER', 'Sulley');
The first two parameters within the brackets are self-explanatory.
The third one, case-insensitive, has a default value of false. Only if it is set to true will the constant be case insensitive.
That is:
define('MONSTER', 'Sulley', true);
Arrays
Arrays are variables that can store more than one thing.
In PHP, arrays are associative arrays or ordered maps. That is to say that the items within the array have related key and value pairs.
<?php
$array(
key => value,
key2 => value2,
...
)
A less abstract example is the following, where the key is a first name and the value the surname.
<?php
$array = array(
"Frodo" => "Baggins",
"Sam" => "Gamgee",
"Merry" => "Brandybuck",
"Pippin" => "Took",
);
For ease of use, you can convert PHP objects to arrays, and convert arrays to objects.
However, JavaScript can only have arrays that have numbered indexes. For example:
var mountains = [
"Everest",
"Kilimanjaro",
"Fuji"
];
To retrieve a value you have to reference the array index, which starts at 0.
var mountain = mountains[1];
Associative arrays with their named indexes are not supported in JavaScript.
Database Integration
One thing that PHP can do brilliantly is connecting to databases. PHP integrates particularly well with MySQL or MariaDB, both of which WordPress uses. A number of PHP frameworks also provide easy database integrations.
Using a database is useful for searching, sorting, and filtering information to present to a user, such as products in an online store.
Historically, JavaScript doesn’t integrate with databases, though that is beginning to change.
PouchDB is one example of a JavaScript database.
Threading
Threading refers to the instructions that a programming language can handle.
PHP is multi-threaded, meaning that it can process multiple instructions in parallel.
The converse is a single-threaded language like JavaScript, which can only handle one command at a time.
To illustrate threading, developer Samim Yaquby uses the analogy of a coffee shop serving customers.
For a small café with a single barista, it’s easier and more efficient for the barista to serve the customers with simpler orders first, one at a time. This resembles JavaScript’s single threading.
By contrast, a large Starbucks would most likely have several baristas fulfilling the same orders simultaneously. This echoes PHP’s multi-threaded approach.
Speed
In general, JavaScript executes faster than PHP on the same hardware. However, because JavaScript runs on the client, if the client machine is old and sluggish, that will have a knock-on effect on the execution time.
PHP speed has improved by leaps and bounds since the release of PHP 7, thanks to a new engine that doubled performance and improved memory consumption. Compared to PHP 5.6, PHP 7.0 can handle more than twice the number of requests, and performance has improved further with each 7.x release.
PHP also runs better than JavaScript when you are building real-time applications such as chatbots or games.
The release of PHP 8 with the Just in Time Compiler is expected to make PHP even faster.
Package Managers
Each language has its own package manager to manage packages: third-party reusable code modules that add extra functionality to a project. Some packages depend on others to run, so they are called dependencies.
PHP has two package managers, PEAR and Composer, which can download PHP packages on the Packagist repository.
JavaScript has several well-known package managers, including npm, Yarn, and Bower.
Out of these, npm is the most popular, with more than 11 million developers using it globally.
Usage on the Web
PHP is the most used server-side language on the web today, easily beating its competition with nearly 80% of websites using it.
While PHP is very popular, JavaScript is near-ubiquitous on websites, with 97% of websites using it.
What Is PHP Used For?
PHP has a wide range of uses.
It is probably best known for creating dynamic web pages. According to BuiltWith, PHP is used by over 34 million websites, and it powers some of the best known and highest-earning sites on the Web, including Nike, Salesforce, and Walmart.
PHP is a perfect fit if your project needs secure authentication of users. This includes cookie and session handling, username and password authentication, and two-factor authentication.
As previously mentioned, PHP is good for working with databases because it can interface with a wide range of them. It also has built-in data security for handling user input, to guard against threats like SQL injection attacks.
PHP is also commonly used for building real-time applications like instant messaging.
Finally, even if you do most of your work on the frontend, you will need a server backend. PHP is an ideal choice as this is what it was created for.
What Is JavaScript Used For?
JavaScript has become so popular that perhaps the right question is, “What isn’t JavaScript used for?”
Aside from websites and web apps, JavaScript has been used to build all of the following:
- Mobile apps
- Web servers
- Games
- Slide decks
- Chatbots
- …and even programmable drones
Can JavaScript Be Used with PHP?
The answer is yes, absolutely.
A common example is with web forms, where it’s useful to validate user input before it’s saved to a database.
You can use JavaScript for client-side validation, e.g. checking an email is in the correct format. Following that, you can use PHP for server-side validation, e.g. checking that the email exists in your database.
How WordPress Uses JavaScript and PHP
Traditionally, WordPress has used both languages, but much more PHP than JavaScript. That has started to change with the introduction of the Gutenberg editor.
In Matt Mullenweg’s State of the Word at WordCamp US in 2015, he gave an idea of how important JavaScript was going to become by urging the audience to
“Learn JavaScript, deeply.”
As things stand, here’s how both languages are used in WordPress.
PHP is used for theme template files, the loop, authentication, validation, and database access.
JavaScript powers theme and plugin interactivity, client-side validation, and event handling. Most notably, some knowledge of JavaScript is required for block development, as blocks are dependent on the React JS framework.
Learning PHP vs JavaScript
As they are fairly easy to learn, there is no reason that you can’t learn both PHP and JavaScript.
The two languages rely on certain programming fundamentals, such as variables, loops, conditional statements, scope, and objects.
Because it is such a well established and popular language, it is easy to learn PHP.
As PHP is a server-side language, you need a server to write code. That could be a real web server, or an emulation of one, such as a local development environment. Some examples are DevKinsta, XAMPP, WAMP, or MAMP.
You can get started learning JavaScript easily enough by practicing in the browser console.
On Chrome browser, you can access the console via the Control+Shift+J shortcut on Windows, or Command+Option+J on Mac.
Where JavaScript gets harder to master is the sheer size of its ecosystem.
The JavaScript language has expanded out from vanilla JavaScript to a plethora of frameworks. Angular, Vue, jQuery, and React are just some of the many that now exist.
A good resource for beginners comes from MDN Web Docs in their JavaScript documentation.
Chris Ferdinandi, who has made a name for himself educating people on vanilla JavaScript, says that JavaScript only really clicked for him after he learned jQuery.
His advice to JS newbies is:
“Don’t get hung up on what order to learn things in. Don’t waste your time trying to pick the perfect thing, because there is no perfect thing.”
Just be aware of the shiny object syndrome with JavaScript frameworks without understanding the fundamentals of HTML and CSS first. HTML underpins everything on the Web, and it can get really broken if it’s mishandled by an over-eager JavaScript developer.
PHP vs JavaScript — Comparison Table
PHP | JavaScript |
Server-side scripting | Client-side scripting |
Used on the backend | Used on the frontend (now full stack with Node.js) |
Only combines with HTML | Combines with multiple languages |
Partly case sensitive | Completely case sensitive |
Syntax differences e.g. # for comments allowed | Syntax differences e.g. # for comments not allowed |
Variables declared with $ prefix | Variables declared with var or let keywords |
Has associative arrays | No associative arrays |
Integrates with many databases | Poor or nonexistent database support |
Multi-threaded | Single-threaded |
Fast if PHP 7.0 or above | Faster than PHP usually |
Uses PEAR and Composer package managers | Uses npm, Yarn, and Bower package managers |
Fast to run if PHP version > 7.x | Generally faster than PHP |
Used on about 80% of websites | Used on nearly all websites |
Summary
In this deep dive into PHP vs JavaScript, there isn’t really one winner. They both have their strengths and weaknesses.
PHP is stable and reliable, while JavaScript has become the cool kid on the block. But that doesn’t mean that one is better than the other.
Whichever one you choose for your next project — and that might be both! — if you take the time to understand the language, you can be sure that you’ll build a website or app that will delight your users.
Big missed bit. PHP been server side is far far harder to hack.
In your form example you would ALWAYS validate in PHP because otherwise someone can simply modify the JD on their computer to bypass the validation and then do nasty things to your DB etc.
Also JS is becoming a lot less useful since a lot of things you had to do in JS before are now directly supported in CSS. You don’t need JS for sliders or accordions anymore, you can do it all in CSS
I hate to tell you but PHP was around before 2004. The two languages have completely different usages, being client side and server side, you use them together, I see no point in comparing them.
PHP was created in 1995, not 2004.
The correction has been made thanks for pointing this out.
But now you can write both client-side and server-side parts of the app with JS, but you can’t do it with only PHP =)