Coding

PHP vs JavaScript: The Differences and Which to Use

PHP vs JavaScript comes down to where the code runs: PHP runs on the web server and sends the browser only its output, while JavaScript runs inside the browser and can also run on a server. They are different languages with different syntax, so most websites that use PHP still use JavaScript for the parts that happen after the page loads.

Here is the same small task in each language, a loop that prints the scores that pass:

<?php
$scores = [72, 85, 90];
foreach ($scores as $score) {
    if ($score >= 80) {
        echo "$score passes\n";
    }
}
// JavaScript
const scores = [72, 85, 90];
for (const score of scores) {
  if (score >= 80) {
    console.log(`${score} passes`);
  }
}

Both print 85 passes and 90 passes. The syntax looks close because both borrow braces and semicolons from the C family. The important differences are elsewhere.

PHP vs JavaScript at a glance

TopicPHPJavaScript
Where it runsOn the server, or from the command lineIn the browser, and on servers through environments such as Node.js
What the browser receivesThe output of the scriptThe JavaScript source itself
VariablesStart with $Declared with let or const
TypingDynamic, with optional type declarationsDynamic, with implicit conversion
Equality== and ===== and ===
Typical jobForms, page generation, database access, cron-style scriptsPage interactivity, plus back ends in Node.js

Where PHP and JavaScript run

The PHP manual describes PHP as "a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML." Its code is executed on the server, generating HTML that is sent to the client. The manual adds that the client "would receive the results of running that script, but would not know what the underlying code was."

You can see this in the manual's first-page example. This file, saved with a .php extension:

<body>
    <?php echo '<p>Hello World</p>'; ?>
</body>

reaches the browser as plain <p>Hello World</p>. The <?php and ?> tags are replaced by whatever the script printed.

Client-side JavaScript works the other way around. MDN explains that "the page's client-side code is downloaded, then run and displayed by the browser." Anyone can read it in the browser's developer tools, so never put secrets in it. MDN also lists PHP and JavaScript together as examples of languages used on the server side, and says JavaScript can run there through environments such as Node.js.

PHP is not limited to web servers. The manual says a script can run from the command line with only the PHP parser, and calls this "ideal for scripts regularly executed using cron (on Unix or macOS) or Task Scheduler (on Windows)."

Syntax differences you will notice first

  • Variable names. PHP variables are "represented by a dollar sign followed by the name of the variable", and the name is case-sensitive, so $var and $Var are two different variables. JavaScript variables have no sigil and are declared with let or const.
  • Tags. A PHP file contains code between <?php and ?>. JavaScript in a page goes in a script element or a separate .js file.
  • Printing. PHP uses echo. JavaScript uses console.log() for debugging output, or changes the page through the DOM.
  • Joining strings. PHP uses the . operator: "a" . "b". JavaScript uses + or template literals with backticks.
  • Arrays. PHP arrays also act as key-value maps. JavaScript separates arrays ([]) from objects ({}).

Typing: both are dynamic, PHP lets you opt in to checks

In both languages a variable can hold a value of any type. PHP adds type declarations on parameters and return values. By default these coerce: the manual says PHP "will coerce values of the wrong type into the expected scalar type declaration if possible." Its example shows a function declared with int parameters accepting 1.5 and 2.5 and returning 3.

Add declare(strict_types=1); at the top of a file and calls made from that file are checked strictly. The manual: "only a value corresponding exactly to the type declaration will be accepted, otherwise a TypeError will be thrown." The one exception is that an int is accepted where a float is declared. Strict mode applies to calls made from within the file that enables it, not to functions declared there.

<?php
declare(strict_types=1);

function sum(int $a, int $b) {
    return $a + $b;
}

var_dump(sum(1.5, 2.5)); // TypeError

Plain JavaScript has no type declarations. If you want compile-time checking in a JavaScript project, the usual route is a typed superset language such as TypeScript.

Equality: == and === in both languages

Both languages have a loose and a strict equality operator. In PHP, $a == $b is true "if $a is equal to $b after type juggling", and $a === $b is true if the values are equal "and they are of the same type." The manual recommends === and !== in most cases because type juggling is not always obvious. The same advice is common in JavaScript; the details are in JavaScript == vs ===.

The two languages do not agree on every loose comparison, so do not carry assumptions across. PHP changed its own rules in version 8.0.0. The manual's example, 0 == "a", was true in PHP 7 and is false in PHP 8, because a non-numeric string is no longer converted to 0. If you read an old PHP tutorial, check which version it was written for.

Which one should you use?

  • You want a page to react to clicks, typing or scrolling. Use JavaScript. Browsers run it natively, and PHP cannot do this because it has finished running before the page arrives.
  • You want to process a form, talk to a database or generate HTML on the server. PHP is built for this. The manual calls server-side scripting its "most widely used and main target field", and notes that database access is simple through extensions such as MySQL or an abstraction layer like PDO.
  • You want one language for everything. JavaScript can cover both sides, with Node.js on the server. You give up nothing in the browser, since you needed JavaScript there anyway.
  • You are maintaining an existing PHP site. Keep PHP on the server and add JavaScript for interactivity. Rewriting working back-end code in another language is rarely the first thing to do.

How the two work together

A typical page uses both. The server runs PHP, which reads from the database and returns HTML or JSON. The browser then runs JavaScript, which can request more JSON from a PHP script without reloading the page. A request from JavaScript looks like this; see how to POST JSON with fetch for the full pattern:

const response = await fetch("/api/scores.php");
const scores = await response.json();

The /api/scores.php path here is a made-up example. The two programs share no variables. Everything crosses as text over HTTP, so PHP only needs to print valid JSON.

If you are comparing JavaScript with other languages, two related pages are Python vs JavaScript and Java vs JavaScript. The second one matters because JavaScript is unrelated to Java despite the name.

Frequently asked questions

Is PHP or JavaScript better for web development?
Neither replaces the other. Browsers run JavaScript, so any interactive page needs it. PHP is one of several server-side languages, and JavaScript can also run on a server through Node.js. Which one you pick for the back end depends on the hosting, the existing code and what you already know.
Can PHP run in the browser?
No. PHP code runs on the server, and the browser receives only the output, usually HTML. The PHP manual says the client would receive the results of running the script but would not know what the underlying code was.
Can JavaScript replace PHP?
Yes, for server-side work. MDN lists JavaScript among server-side languages next to PHP, Python, Ruby and C#, and it can run on a server through environments such as Node.js. You would then write the whole site in one language.
Do PHP and JavaScript work together?
Yes. A common pattern is a PHP script that builds the page or returns JSON, and JavaScript in the page that requests that JSON and updates the display. The two languages never share variables directly; data crosses the boundary as text over HTTP.

Sources